Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading