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

时间:2013-12-03 15:59:27

标签: 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
    }
}

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

2 个答案:

答案 0 :(得分:62)

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

答案 1 :(得分:7)

你可以这样做

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