Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checked Exception 2 kinds of behaviours

I have noticed that there are 2 kinds of checked exceptions:

1)

public static void main (String []args)
{
    try{
        //no exception thrown here, it still compiles though.
    }
    catch(Exception e){System.out.println(e);}
}

2)

public static void main (String []args)
{
    try{
         // it does not compile if not written any code which potentially might throw it
    }
    catch(IOException io){System.out.println(io);}
}

Is there any rule to anticipate this behaviour? to know in advance which is not mandatory to be present and it is? Hope I have been quite clear with explaining the issue. Thanks, Indeed ItIs

like image 579
Indeed ItIs Avatar asked Jan 12 '23 07:01

Indeed ItIs


2 Answers

The Java Language specification states

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.

like image 169
Sotirios Delimanolis Avatar answered Jan 25 '23 10:01

Sotirios Delimanolis


The code compiles fine with Exception, because it is a super class of all Checked and Unchecked exceptions. So, a catch clause with Exception can handle the unchecked exception too. And for Unchecked exception, compiler cannot check at compile time that the exception is thrown or not. So, it won't give any error for Exception.

You can even try this with RuntimeException:

try {

} catch (RuntimeException e) {

}

... this will compile too.

From JLS Section 11.2.3 - Exception Checking:

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.

like image 21
Rohit Jain Avatar answered Jan 25 '23 09:01

Rohit Jain