【问题标题】:How to catch all exceptions except a specific one?如何捕获除特定异常之外的所有异常?
【发布时间】:2013-12-03 15:59:27
【问题描述】:

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

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
    }
}

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

【问题讨论】:

标签: java exception


【解决方案1】:
void myRoutine() throws SpecificException { 
    try {
        methodThrowingDifferentExceptions();
    } catch (SpecificException se) {
        throw se;
    } catch (Exception e) {
        //default routine for all other exceptions
    }
}

【讨论】:

  • 这种方法确实回答了这个问题。但是,它的缺点是重新抛出的se 异常保留了其原始堆栈跟踪;因此,myRoutine 重新抛出异常并不明显。这可能会使调试变得困难。 Wrapping the exception instead of re-throwing it 通常会更好。
【解决方案2】:

你可以这样做

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

【讨论】:

  • 此答案未遵循 Java Clean Code 指南。看 Dodd10x 的答案。
猜你喜欢
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 2018-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
相关资源
最近更新 更多