javaexceptionruntimeexception

How does exception chain work in my code?


Why this code doesn't print "d". Why it doesn't go to the catch block for RunTimeException?

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

The output of this program is

a
b
c
e
Exception in thread "main" java.lang.RuntimeException

EDIT: After throwing IllegalArgumentException it goes to the corresponding catch block and prints 'c'. after that since we don't catch the exception in RuntimeException it doesn't go any further. but since it's guranteed that we go to the finally block it print 'e' and after that throw RunttimeException. if the code was like something like the following, it would throw out the RuntimeException("2"). If we comment the exception inside finally, it throw out RuntimeException("1").

public static void main(String[] args) throws InterruptedException {
            System.out.println("a");
            try {
                System.out.println("b");
                throw new IllegalArgumentException();
            } catch (IllegalArgumentException e) {

                    System.out.println("c");
                    throw new RuntimeException("1");

            }catch (RuntimeException e) {
                System.out.println("d");
                throw new RuntimeException();
            }finally{
                System.out.println("e");
                throw new RuntimeException("2");
            }
        }

Solution

  • In try catch block, if one of the catch block catches the exception the other catches doesn't get involved. remeber that finally block always run at the end no matter exception gets threw or not.