简体   繁体   English

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

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

I want to new a url object, and do something with the url. 我想新建一个url对象,并对该url做一些事情。

For example, 例如,

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

The code doesn't compile because the URL constructor declares MalformatedException , I have to either declare the exception or try-catch it. 该代码无法编译,因为URL构造函数声明了MalformatedException ,我必须声明该异常或尝试捕获该异常。 But I think none of two ways make sense, because the url string doesn't change, this exception is impossible to be thrown. 但是我认为两种方法都没有道理,因为url字符串没有变化,因此无法抛出此异常。

How should I deal with this situation? 我应该如何处理这种情况?

You can do this: 你可以这样做:

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

This way the exception is still thrown if you are wrong but you don't have to deal with it if you are really sure it won't happen. 这样,如果您错了,仍然会引发异常,但是如果您确实确定不会发生异常,则不必处理该异常。 This is probably not appropriate for production code. 这可能不适用于生产代码。 If the program is important to someone that's not you, a better solution may be to log it in the appropriate manner. 如果该程序对不是您的人很重要,则更好的解决方案是以适当的方式记录该程序。

You really can't be sure an exception will never throw, I've personally had it happen a couple of times where I was pretty sure it wouldn't and it did. 您确实不能确定异常永远不会抛出,我个人已经有几次发生过这种情况,而我非常确定不会发生并且确实如此。

The other way is to handle it in a sissy way: 另一种方法是以娘娘腔的方式处理它:

// 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!");
    }
}

You could just surround it in a try/catch like so from my understanding. 根据我的理解,您可以像这样尝试/捕获它。

void downloadPage()
{

try {

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

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


}

Try catching it is the best way to go about it. 尝试抓住它是最好的方法。 This also protects you in case you accidentally edit the url to http//www.google.com . 如果您不小心将网址修改为http//www.google.com这也可以为您提供保护。

You have to declare it or try-catch it. 您必须声明它或尝试捕获它。 There is no other way. 没有别的办法了。

Compiler is not able to "check" if your address is malformated or not before running it. 在运行地址之前,编译器无法“检查”您的地址是否格式错误。

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

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