2

Please find my code below, I want to clear my concept on overriding along with throws exceptions. Will below provided code work, if yes then why.? I'm asking this question because there is no direct parent child relation between IOException and ArithmeticException.

public class TestExceptionChild {

    public static void main(String[] args) {
        Parent parent = new Child();
        try {
            parent.msg();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Parent{  
    void msg() throws IOException{
        System.out.println("parent");
    }  
}

class Child extends Parent{  
    void msg() throws ArithmeticException{
        System.out.println("child");
    }  
}
Raj Bhatia
  • 1,049
  • 4
  • 18
  • 37

1 Answers1

1

This will work, but only because ArithmeticException extends RuntimeException (i.e. it is not a checked exception, so the use of a throws clause here is unnecessary). If instead of ArithmeticException, you use a checked exception, it must be or extend type IOException. Otherwise, you will get a compile error.

So to answer your question, yes, hierarchy is important for checked exceptions. See here for more details.

Community
  • 1
  • 1
pathfinderelite
  • 3,047
  • 1
  • 27
  • 30
  • 1
    `IOException` isn't a `RuntimeException`, though. Why is the overriden method not required to also have `throws IOException`? How come it can throw *nothing*, but not throw another kind of checked exception? – RaminS Nov 06 '16 at 18:02
  • @Gendarme You can think of "throws nothing" as a subset of `throws IOException`. The inverse is not true, however. If the parent throws nothing, the overridden child cannot throw a checked exception. – pathfinderelite Nov 06 '16 at 18:05
  • I would add that to the answer. – shmosel Nov 06 '16 at 18:09
  • So does that mean hierarchy doesn't matter for a scenario where parent method its throwing checked exceptions and child throws unchecked exceptions..? – Raj Bhatia Nov 06 '16 at 18:37
  • @RajBhatia `throws` is for checked exceptions. Excluding documentation purposes, it is meaningless for unchecked exceptions. – pathfinderelite Nov 06 '16 at 18:50