Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bypass java exception specification...?

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?

like image 341
OppfinnarJocke Avatar asked Jan 07 '12 15:01

OppfinnarJocke


People also ask

How do I skip an exception?

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.

How do I fix exception error in Java?

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.

Can you ignore a checked exception in Java?

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.

How do you ignore an exception thrown in Java?

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.


1 Answers

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.

like image 71
Roger Lindsjö Avatar answered Oct 04 '22 22:10

Roger Lindsjö