1

I am referring to Why can't overriding methods throw exceptions broader than the overriden method?

but How it can be possible in case of UncheckedException or RunTimeException to declare a parent exception in child class-

import java.io.*;

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

class Child extends Parent {
    public static void main(String args[]) {
        Parent p = new Child();
        try {
            p.msg();
        } catch (NullPointerException e) {
            System.out.println(e);
        }
    }

    void msg() throws RuntimeException {
        System.out.println("child");
    }
}

Is it since compiler is not responsible to handle with unchecked Exception.

Also one more point here I am handling it with child exception (NullPointerException) and this is not showing me any compile fail.

Community
  • 1
  • 1
  • 3
    Read the _second_ answer to the question you linked. – GriffeyDog May 05 '15 at 14:10
  • Are you referring to the apache `UncheckedException` that extends java's `RuntimeException`? If so, could you please specify in the question? – Captain Man May 05 '15 at 14:37
  • this is saying fact not why?Actually I am unable to understand how this does not cause any issue but restricted in case of checked Exception? –  May 05 '15 at 15:01

1 Answers1

1

The point of restricting checked exceptions thrown by subclasses is so the caller can be certain that the subclass doesn't throw anything in addition to what the superclass can throw (enabling the caller to treat the subclass the same as the superclass, see LSP). That kind of certainty is not possible with unchecked exceptions.

If I declare a method to throw IllegalArgumentException, obviously that doesn't stop it from throwing NullPointerException. It doesn't do any good for the compiler to warn the user about cases where a method is overridden in a subclass to throw a broader range of unchecked exceptions; since any unchecked exception can get thrown regardless of whether it is declared, the user has no more certainty with the warning than without it. Therefore the compiler ignores any unchecked exceptions that show up in a throws clause of a method declaration.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276