繁体   English   中英

如何处理不可能引发的检查异常

[英]How to deal with checked exception that is impossible to be thrown

我想新建一个url对象,并对该url做一些事情。

例如,

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

该代码无法编译,因为URL构造函数声明了MalformatedException ,我必须声明该异常或尝试捕获该异常。 但是我认为两种方法都没有道理,因为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!");
    }
}

根据我的理解,您可以像这样尝试/捕获它。

void downloadPage()
{

try {

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

} catch(MalformedException me) { 
     System.out.println("caught this: " + me);
}


}

尝试抓住它是最好的方法。 如果您不小心将网址修改为http//www.google.com这也可以为您提供保护。

您必须声明它或尝试捕获它。 没有别的办法了。

在运行地址之前,编译器无法“检查”您的地址是否格式错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM