简体   繁体   中英

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?

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.

Try the following:

public class Settings
{
    static final URL logo;

    static
    {
        try 
        {
            logo = new URL("http://www.example.com/pic.jpg");
        } 
        catch (MalformedURLException e) 
        {
            throw new IllegalStateException("Invalid URL", e);  
        }
    }
    // and other static final stuff...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM