I want to do
public class Settings
{
static final URL logo = new URL("http://www.example.com/pic.jpg");
// and other static final stuff...
}
but I get told that I need to handle MalformedURLException
. THe specs say that MalformedURLException
is
Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
Now, I know that the URL I give is not malformed, so I'd rather not handle an exception I know cannot occur.
Is there anyway to avoid the unnecessary try-catch-block clogging up my source code?
There is no way to basically ignore a thrown exception. The best that you can do is to limit the standard you have to wrap the exception-throwing code in.
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
No, it raises a compiler error. Being a checked exception, you must either catch it or propagate it by declaring your method as potentially throwing it.
To ignore an exception in Java, you need to add the try... catch block to the code that can throw an exception, but you don't need to write anything inside the catch block.
Shortest answer is no. But you could create a static utility method to create the URL for you.
private static URL safeURL(String urlText) {
try {
return new URL(urlText);
} catch (MalformedURLException e) {
// Ok, so this should not have happened
throw new IllegalArgumentException("Invalid URL " + urlText, e);
}
}
If you need something like this from several places you should probably put it in a utility class.
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