A uri
could 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 is a better practice. I haven't noticed any performance differences and I've read the documentation, however it was a bit difficult to understand. Any insight on this is appreciated.
create. Creates a URI by parsing the given string. This convenience factory method works as if by invoking the URI(String) constructor; any URISyntaxException thrown by the constructor is caught and wrapped in a new IllegalArgumentException object, which is then thrown.
Uniform Resource Identifier (URI) − a sequence of characters that allows the complete identification of any abstract or physical resource.
A Uri object is usually used to tell a ContentProvider what we want to access by reference. It is an immutable one-to-one mapping to a resource or data. The method Uri. parse creates a new Uri object from a properly formated String .
Reading the docs, it differs in the usage.
Creates a URI by parsing the given string.This convenience factory method works as if by invoking the {@link URI(String)} constructor; any {@link URISyntaxException} thrown by the constructor is caught and wrapped in a new {@link IllegalArgumentException} object, which is then thrown.
This method is provided for use in situations where it is known that the given string is a legal URI, for example for URI constants declared within in a program, and so it would be considered a programming error for the string not to parse as such. The constructors, which throw {@link URISyntaxException} directly, should be used situations where a URI is being constructed from user input or from some other source that may be prone to errors.
@param str The string to be parsed into 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); } }
There is no difference because URI.create
delegates the call to the constructor. The only real difference is that URI.create(String)
wraps the URISyntaxException
which the constructor throws (checked exception) into an IllegalArgumentException
(unchecked exception). So if you don't want to deal with the checked exception it's better to just call URI.create(String)
.
Here is the piece of code from JDK:
public static URI create(String str) { try { return new URI(str); } catch (URISyntaxException x) { throw new IllegalArgumentException(x.getMessage(), x); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With