URI.create () vs new URI ()

A uri can be created in two ways:

 URI uri = new URI("https://www.google.com/"); 

Or

 URI uri = URI.create("https://www.google.com/"); 

I was wondering which one is better. I did not notice any differences in performance, and I read the documentation, however it was a little difficult to understand. Any understanding of this is appreciated.

+10
source share
2 answers

Reading documents, it is different in use.

Creates a URI by parsing the given string. This convenience factory method works as if you were calling {@link URI (String)}; any {@link URISyntaxException} thrown by the constructor is caught and wrapped in a new {@link IllegalArgumentException}, which is then thrown.

This method is intended for use in situations where it is known that this string is a legal URI , for example, for URI constants declared internally in the program, and therefore it will be considered as a programming error for the string, so as not to analyze as such. constructors that directly throw {@link URISyntaxException} should use situations where the URI is created from user input or from another source that may be error prone.

@param str String to be parsed in a URI

  * @return The new URI * * @throws NullPointerException * If {@code str} is {@code null} * * @throws IllegalArgumentException * If the given string violates RFC 2396 */ 
 public static URI create(String str) { try { return new URI(str); } catch (URISyntaxException x) { throw new IllegalArgumentException(x.getMessage(), x); } } 
+14
source

There is no difference because URI.create delegates the call to the constructor. The only real difference is that URI.create(String) URISyntaxException the URISyntaxException which is the constructor of URISyntaxException (checked exception) is in IllegalArgumentException (unchecked exception), so if you don't want to deal with the checked exception, it's better to simply call the URI. create (String)

Here is a piece of code from the JDK:

 public static URI create(String str) { try { return new URI(str); } catch (URISyntaxException x) { throw new IllegalArgumentException(x.getMessage(), x); } } 
0
source

All Articles