Omer Gillani Omer Gillani - 1 month ago 8
Java Question

Catching checked exception which is not thrown in try clause

Java does not allow to catch checked exception which is not thrown in try clause

try {

} catch(IOException e) {

}



Unreachable catch block for IOException. This exception is never
thrown from the try statement body


Why does below code compile fine?

try {

} catch(Exception e) {

}


Exception and IOException both are checked exception.

Answer

Exception itself is checked, but it is also the superclass of RuntimeException, which is not. catch(Exception) can catch unchecked exceptions, and is therefore not checked by the compiler to see if the try block actually throws such an exception.

Comments