绕过java异常规范......?

时间:2012-01-07 15:10:57

标签: java exception-handling

我想做

public class Settings
{
    static final URL logo = new URL("http://www.example.com/pic.jpg");
    // and other static final stuff...
}

但我被告知我需要处理MalformedURLException。规范说MalformedURLException

  

抛出表示发生格式错误的网址。要么在规范字符串中找不到合法的协议,要么无法解析字符串。

现在,我知道我提供的URL没有格式错误,所以我宁愿不处理我知道不会发生的异常。

无论如何都要避免不必要的try-catch-block堵塞我的源代码?

2 个答案:

答案 0 :(得分:12)

最短的答案是否定的。但您可以创建一个静态实用程序方法来为您创建URL。

 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);  
     }
 }

如果你需要从几个地方做这样的事情,你应该把它放在一个实用工具类中。

答案 1 :(得分:4)

尝试以下方法:

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...
}
相关问题