I'm using Eclipse, it give me a compilation error when i use this Code
Unreachable catch block for IOException. This exception is never thrown from the try statement body
public void f() {
try {
System.out.println("");
} catch (IOException e) {
// TODO: handle exception
}
}
but when i use Exception instead of IOException it compile, both are checked exceptions, waht am i doing wrong
catch (Exception e)
is a special case in the Java Language Specification. The rule is
It is a compile-time error if a
catch
clause can catch checked exception classE1
and it is not the case that thetry
block corresponding to thecatch
clause can throw a checked exception class that is a subclass or superclass ofE1
, unlessE1
isException
or a superclass ofException
.
catch (IOException e)
can only catch IOException
and its subclasses, which are all checked exceptions.
On the other hand, catch (Exception e)
can catch RuntimeException
and its subclasses (among other things), which are not checked exceptions. Therefore, it cannot be concluded that the catch
block will never be executed.