EDIT: Seems that I sounded too annoyed in the first, here is a rework.
I'd like to create an URL constant, like so
public static final URL REMOTE_URL = new URL("http://example.com/");
But I can't since the constructor throw a checked exception. Right now I use
public static final URL REMOTE_URL = createUrl("http://example.com/");
private static URL createUrl(String url) {
try {
return new URL(url);
} catch (MalformedURLException error) {
throw new IllegalArgumentException(error.getMessage(), error);
}
}
But it feel like reinventing the wheel. I can't possibly be the only one who want to use a URL constant no? So I was wondering if there is third-party toolbox library (like guava or apache-commons, or something else, anything) or even better, something in standard Java that include this facilities? That would help me when we start a new project by reducing the size of our util package :) .
A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled.
The URL class provides several methods that let you query URL objects. You can get the protocol, authority, host name, port number, path, query, filename, and reference from a URL using these accessor methods: getProtocol.
URL Parsing. The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.
This complaint must have been a common one, because Java has (since 1.7) introduced the URI class. This class has two ways of constructing it:
For URIs/URLs like yours that are known to come from a safe source, you can use the URI.create() variant and not have to worry about catching the exception as you know it won't be thrown.
Unfortunately, sometimes you can't use a URI and you still need a URL. There's no standard method (that I have found so far) of converting a URI into a URL that doesn't throw a checked exception.
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