Java 如何捕获除特定异常之外的所有异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20355824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:19:20  来源:igfitidea点击:

How to catch all exceptions except a specific one?

javaexception

提问by membersound

Is it possible to catch all exceptions of a method, except for a specific one, which should be thrown?

除了应该抛出的特定异常之外,是否可以捕获方法的所有异常?

void myRoutine() throws SpecificException { 
    try {
        methodThrowingDifferentExceptions();
    } catch (SpecificException) {
        //can I throw this to the next level without eating it up in the last catch block?
    } catch (Exception e) {
        //default routine for all other exceptions
    }
}

/Sidenote: the marked "duplicate" has nothing to do with my question!

/旁注:标记的“重复”与我的问题无关!

采纳答案by Dodd10x

void myRoutine() throws SpecificException { 
    try {
        methodThrowingDifferentExceptions();
    } catch (SpecificException se) {
        throw se;
    } catch (Exception e) {
        //default routine for all other exceptions
    }
}

回答by Prabhakaran Ramaswamy

you can do like this

你可以这样做

try {
    methodThrowingDifferentExceptions();    
} catch (Exception e) {
    if(e instanceof SpecificException){
      throw e;
    }
}