What you could do is initialize the Url in a static block or in a `{{ }}` block and handle the exception there. You would still have the exception handling, but not in your logic, and the static block would ensure that if the Url is indeed malformed, the exception will throw as soon as the class is loaded in memory, instead of only when the Url is instantiated during in logic.
So somewhere up in your class, you'd write:
private final static URL someUrl;
static {
try {
someUrl = new URL("http://something.com/");
} catch(SomeException e) {
crashAndLogSomehow(e);
}
}
You would thus know right when you load your app, before distributing it, whether an exception can happen. In your code, you wouldn't have the try/catch block hiding the real meaning.
Putting it in a static block is bad advice, there are many other places you could put initialization.
What happens if a static block throws an exception is that the class will not be loaded, and every other time the code refers to the class it will get a ClassDefNotFoundException, which can lead to a 'fun' time tracing the actual issue. Hence why static blocks are not used very much (though it can be convenient).
The idea is that if an exception has to be thrown, it will throw as early as possible, making it pretty obvious during development that there's a bug - whenever you try to run your app it will exit with an error about the MalformedUrl. Notice I said he/she should catch the exception in the static block and log it, pretty hard to have an issue tracking where the error comes from.
You can't check at compile time that the Url is valid, but if as soon as you load the program, it crashes with this exception, it will be hard to ignore and the mistake won't be hidden. Since you catch the exception that's thrown a static time, there's no ClassDefNotFoundException.
Thanks, that's a better solution. I still dislike having to handle something that'll never happen, but this is probably the best one can do in this case.
So somewhere up in your class, you'd write:
You would thus know right when you load your app, before distributing it, whether an exception can happen. In your code, you wouldn't have the try/catch block hiding the real meaning.