gpt4 book ai didi

java - 如何处理不可能抛出的已检查异常

转载 作者:行者123 更新时间:2023-11-30 04:00:38 24 4
gpt4 key购买 nike

我想新建一个 url 对象,并对该 url 执行一些操作。

例如,

void downloadPage()
{
URL url=new URL("http://www.google.com");
do(url);
}

代码无法编译,因为 URL 构造函数声明了 MalformatedException,我必须声明异常或 try catch 它。但我认为这两种方式都没有意义,因为url字符串没有改变,这个异常是不可能抛出的。

遇到这种情况我该如何处理?

最佳答案

你可以这样做:

try {
throwsCheckedException();
} catch(CheckedException e) {
throw new RuntimeException(e);
}

这样,如果你错了,仍然会抛出异常,但如果你确实确定它不会发生,则不必处理它。这可能不适合生产代码。如果该程序对您以外的其他人很重要,更好的解决方案可能是以适当的方式记录它。

你真的不能确定异常永远不会抛出,我个人已经发生过几次这种情况,我很确定它不会抛出,但它确实抛出了。

另一种方式就是以娘娘腔的方式处理:

// in some utility class
public static void exitWithError(Throwable e, String msg) {
dumpStackTraceToFile(e); // something you should have
JOptionPane.showMessageDialog(null, msg);
System.exit(1); // force JVM exit when the dialog closes
}

// wherever this should be, only do it once
static final URL GOOGLE;
static {
try {
GOOGLE = new URL("http://google.com");
} catch(MalformedURLException e) {
exitWithError(e, "Somebody changed the Google URL!");
}
}

关于java - 如何处理不可能抛出的已检查异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22085734/

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