puvi
puvi

Reputation: 231

In calling method why Exception can be caught without throwing and why subclass of exception cannot be caught without throwing

Catching an exception for a method which does not throw a subclass of exception in try block, fails to compile. when I catch Exception it works. How does it work??

This code below does not compile !!

class Test
{
    public static void main(String[] args) {
        try {
            myMethod();
        } catch(MyException ex) {//Does not compile
        }
    }

    public static void myMethod() {}
}

class MyException extends Exception {}


But when Exception is caught, compiler does not complain.

class test
{
    public static void main(String[] args)
    {
        try{
            myMethod();
        } catch(Exception ex) {//how does this works ??
        }
    }

    public static void myMethod() {}
}

Upvotes: 1

Views: 39

Answers (2)

Rahman
Rahman

Reputation: 3785

MyException is a checked exception. It was never thrown from your myMethod() method . So catch block will be unreachable.

But Exception is a super class of checked and unchecked(runtime) exception and if any runtime exception thrown from myMethod() it will be handled in catch block which is a possible scenario. Hence there is no compilation error.

Upvotes: 0

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

From the JLS (§11.2.3): (emphasis mine)

It is a compile-time error if a catch clause can catch checked exception class E1 and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 is Exception or a superclass of Exception.

Upvotes: 3

Related Questions