javaexceptionthrows

Exception doesn't need to be thrown to be caught, but IOException does


Why does the following code compile fine, but the method being called does not need to throw Exception? Isn't Exception a checked exception and not an unchecked exception? Please clarify.

class App {
    public static void main(String[] args) {
        try {
            amethod();
            System.out.println("try ");
        } catch (Exception e) {
            System.out.print("catch ");
        } finally {
            System.out.print("finally ");
        }
        System.out.print("out ");
    }
    public static void amethod() { }
}

If I want to use a try catch with IOexception (a checked exception), the method being called needs to throw IOException. I get this.

import java.io.IOException;

class App {
    public static void main(String[] args) {
        try {
            amethod();
            System.out.println("try ");
        } catch (IOException e) {
            System.out.print("catch ");
        } finally {
            System.out.print("finally ");
        }
        System.out.print("out ");
    }
    public static void amethod() throws IOException { }
}

Solution

  • Isn't 'Exception' a checked exception and not an unchecked exception?

    Yes, it is.

    But even if we know the method doesn't throw Exception itself, the code catch(Exception e){ could still execute. The code in the try block could still throw something that inherits from Exception. That includes RuntimeException and its subclasses, which are unchecked.

    catch(IOException e){, on the other hand, can only catch checked exceptions. (Java doesn't allow multiple inheritance, so anything that's a subclass of IOException can't possibly be a subclass of RuntimeException.) The compiler can fairly easily figure out that none of the code in the try block can possibly throw an IOException (since any method throwing a checked exception must explicitly say so) which allows it to flag the code.