Java bypass 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 they told me what I need to process MalformedURLException. Specifications say there MalformedURLExceptionare

Emphasized that an invalid URL has occurred. Either no legal protocol can be found in the specification line, or the line cannot be analyzed.

Now I know that the URL I am giving is not garbled, so I prefer not to handle the exception, which, as I know, cannot happen.

Anyway, to avoid unnecessarily blocking the try-catch block associated with my source code?

+5
source share
2 answers

The shortest answer is no. But you can 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);  
     }
 }

- , , , .

+12

:

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...
}
+4

All Articles