tags:

views:

50

answers:

2

If you have:

catch (FooException ex) {
    throw new BarException (ex);
}
catch (BarException ex) {
    System.out.println("hi");
}

...and the first catch clause is triggered (i.e. FooExcepetion has occurred), does the new BarException get immediately caught by the subsequent "catch" clause?

Or is the new BarException thrown one level up the continuation stack?

I realize this is a basic question. : )

+2  A: 

It's thrown one level up.

You'll need another try//catch block.

Colin Hebert
+4  A: 

It does not get caught by the 2nd catch clause, no.

Each catch clause in the list is tried, to see if it matches. The first one that matches is the only one that runs, then the code moves on to the finally clause.

Another result of this is that if you have:

try {
    throw SubTypeOfException(...);
} catch(Exception e) {
    ... block 1 ...
} catch(SubTypeOfException e) {
    ... block 2 ...
}

then block 1 is the only one that will run, even though block 2 would have matched. Only the first matching catch clause is evaluated.

RHSeeger
Yup, I knew about this -- i.e. you should always list your catch clauses in decreasing order of Exception specificity.I long for Java 7's catch(ExceptionType1 | ExceptionType2 ex) syntax....
Aaron F.
Indeed, that will be a nice addition.
RHSeeger
@Aaron F. Wow! I can't wait for that!!
Shakedown