gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:14:01 25 4
gpt4 key购买 nike

我想做

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

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

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.

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

有没有办法避免不必要的 try-catch-block 阻塞我的源代码?

最佳答案

最短的答案是否定的。但是您可以创建一个静态实用程序方法来为您创建 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);
}
}

如果你需要从多个地方得到这样的东西,你应该把它放在一个实用类中。

关于java - 绕过 Java 异常规范...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8770639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com