0

I've come across an exercise while preparing my OCA, i don't understand why the program print : abce 3 instead of abcde 3. Here the program :

'public static void main(String[] args) {
        System.out.print("a");
         try{
            System.out.print("b");
             throw new IllegalArgumentException();
          }catch(IllegalArgumentException e){
              System.out.print("c");
              throw new RuntimeException("1");
          }catch(RuntimeException e) {
              System.out.print("d");
              throw new RuntimeException("2");
          }finally {
            System.out.print("e");
            throw new RuntimeException("3");
          }
        }'

Any explanations why it ignores the last catch block will be really appreciated!

kourouma_coder
  • 1,078
  • 2
  • 13
  • 24
  • 1
    `Another problem is that the exception thrown in the last catch block is simply ignored or masked by the one thrown in the finally block`. Yes, that is a problem, but it's a problem built into Java :) Don't throw exceptions from finally blocks. – biziclop Dec 22 '16 at 21:55

1 Answers1

5

A finally block is always executed after a try-catch block, therefore e is printed. abc are obvious, as you throw an exception in try and the corresponding catch block for IllegalArgumentException is entered.

However, since you throw a new exception RuntimeException inside the catch block, it is thrown to the caller of your method. The catch blocks only handles exceptions thrown in a try block, all others are passed on to the caller of the function you throw the exception in.

thatguy
  • 21,059
  • 6
  • 30
  • 40