The following code compiles ok even though the try block doesn't actually throw any Exception.
public static void main(String[] args) {
try {}
catch (Exception e) {} // compiles ok
}
But if the catch is replaced with a sub-class of Exception, the code won't compile.
public static void main(String[] args) {
try {}
catch (IOException e) {} // won't compile.
}
The compiler error is: Unreachable catch block for IOException. This exception is never thrown from the try statement body.
How come this behavior when both Exception & IOException are checked exceptions? I'm using Java 7.
The compiler can know exactly what part of the code can throw an IOException
because it is a checked exception, so every method that can throw this kind of exception must specify it in the method signature.
On the other hand, runtime or unchecked exceptions are not meant to be expected, and since RuntimeException
(the parent class of unchecked exceptions) also extends the class Exception
, then the compiler is ok with it.
Exception
has subclasses that are unchecked exceptions (RuntimeException
extends Exception
). Throwable
will behave similarly. RuntimeException
or subclasses of RuntimeException
will behave similarly. Subclasses of Exception
other than RuntimeException
will not.
Manouti's answer seems correct, but according to the java documentation:
It is a compile-time error if a catch clause catches checked exception type E1 but there exists no checked exception type E2 such that all of the following hold:
E2 <: E1 The try block corresponding to the catch clause can throw E2 No preceding catch block of the immediately enclosing try statement catches E2 or a supertype of E2. unless E1 is the class Exception.
There is an explicit case for the throwing of an Exception
instance (the Exception
class is exceptional, one might say). This is the Java 5 documentation, but unless someone sees otherwise, I highly doubt this has changed since
Looking at the inheritance tree for Exception
and IOException
https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
and
https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html?is-external=true
in Java 7, I don't see that the discussion on Checked/Unchecked exceptions is directly relevant - while it's true that unchecked exceptions don't follow the same rules, unchecked exceptions must inherit from RuntimeException
, which Exception
of course does not (it is the parent of that class)
https://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#308526
(again, Java 5 docs, but it hasn't changed) https://docs.oracle.com/javase/specs/jls/se5.0/html/exceptions.html
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