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

mem*_*und 45 java exception

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Dod*_*10x 74

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

  • 这种方法确实回答了这个问题。然而,它有一个缺点,即重新抛出的“se”异常保留其原始堆栈跟踪;因此,“myRoutine”重新抛出异常并不明显。这可能会使调试变得困难。[包装异常而不是重新抛出异常](https://www.baeldung.com/java-wrapping-vs-rethroing-exceptions)通常会更好。 (3认同)

Pra*_*ran 10

你可以这样做

try {
    methodThrowingDifferentExceptions();    
} catch (Exception e) {
    if(e instanceof SpecificException){
      throw e;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案没有遵循 Java Clean Code 指南。看看Dodd10x的答案。 (2认同)