82

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!

membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • yes I did not know that I can just rethrow it... – membersound Dec 03 '13 at 16:04
  • 2
    Possible duplicate of [How can I catch all the exceptions that will be thrown through reading and writing a file?](https://stackoverflow.com/questions/1075895/how-can-i-catch-all-the-exceptions-that-will-be-thrown-through-reading-and-writi) – BuZZ-dEE Apr 16 '19 at 11:03

2 Answers2

134
void myRoutine() throws SpecificException { 
    try {
        methodThrowingDifferentExceptions();
    } catch (SpecificException se) {
        throw se;
    } catch (Exception e) {
        //default routine for all other exceptions
    }
}
Dodd10x
  • 3,344
  • 1
  • 18
  • 27
  • 3
    This approach does answer the question. However, it has the drawback that the re-thrown `se` exception retains its original stacktrace; and therefore it would not be evident that `myRoutine` re-threw the exception. This could make debugging difficult. [Wrapping the exception instead of re-throwing it](https://www.baeldung.com/java-wrapping-vs-rethrowing-exceptions) would be generally better. – cybersam Jan 15 '21 at 02:47
13

you can do like this

try {
    methodThrowingDifferentExceptions();    
} catch (Exception e) {
    if(e instanceof SpecificException){
      throw e;
    }
}
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64