Opp*_*cke 5 java exception-handling
我想要做
public class Settings
{
static final URL logo = new URL("http://www.example.com/pic.jpg");
// and other static final stuff...
}
Run Code Online (Sandbox Code Playgroud)
但我被告知我需要处理MalformedURLException.规格说MalformedURLException是
抛出以指示发生了格式错误的URL.无论是没有法律协议可能会在规范字符串中找到或字符串无法解析.
现在,我知道我提供的URL没有格式错误,所以我宁愿不处理我知道不会发生的异常.
反正有没有避免不必要的try-catch-block堵塞我的源代码?
Rog*_*sjö 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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你需要从几个地方这样的东西,你应该把它放在一个实用工具类.