javaexceptionunreachable-codedefensive-programming

Exception Class declared but not thrown


Here test is not throwing an Exception object , yet i had handled it . Since Exception is an checked exception shouldn't it throw a compiler error of unreachable code in the catch block

class Ece extends Exception {}
public class Excep {
    public static void test()  { }
    public static void main(String[] args) {
        try {
            test();
        } catch (Exception E) {

        }
    }
}

Solution

  • The class Exception has RuntimeException as subclass. RuntimeException and its subclasses do not need to be declared in methd signature.

    In this case you are catching all possible subclasses of Exception, including all that subclasses that do not need signature declaration. If your test method throws for example ArrayIndexOutOfBoundsException you will be able to catch and handle it, yet test signature will not be affected.

    Further reading here