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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With