javaexceptionioexception

Java error compilation while using checked exception


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


Solution

  • 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 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.

    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.