Why do Exception classes that extend the base Java Exception class not get caught?

42 Views Asked by At

Given the following program:

public class App {
    public static void main(String[] args) throws Exception {
        int x = 0;
        try {
            throw new Exception2();
        }
        catch (Exception e) {x += 1;}
        catch (Exception1 e) {x += 2;}
        catch (Exception2 e) {x += 3;}
    }
}


class Exception1 extends Exception {

}

class Exception2 extends Exception1 {

}

Both catch lines with Exception1 and Exception2 are giving an error that they are unreachable. Why exactly is this? I am throwing a new Exception2 and so I would expect the Exception2 catch block to run.

1

There are 1 best solutions below

0
ControlAltDel On

The problem is simply the order in which you are catching the exception. Start from the most specific Exception classes and end with the most broad (ie Exception)

public class App {
    public static void main(String[] args) throws Exception {
        int x = 0;
        try {
            throw new Exception2();
        }
        catch (Exception2 e) {x += 3;}
        catch (Exception1 e) {x += 2;}
        catch (Exception e) {x += 1;}
    }
}


class Exception1 extends Exception {

}

class Exception2 extends Exception1 {

}