Throw Error, Exception and Runtime Exception in child class

I'm trying to understand the difference why a child class cannot override a method implementation in the parent class to catch an Exception but no problem while catching a Error,

For example in the below scenario, when I remove "Exception" from the throws clause, it compiles fine.

class Supertest {

    public void amethod(int i, String s) {

    }

}

public class test extends Supertest {

    public void amethod(int i, String s) throws Error, Exception {

    }

}
Jon Skeet
people
quotationmark

Error is an unchecked exception. Exception is a checked exception. It's as simple as that. So it should be reasonable to have code like this:

Supertest x = new test();
x.amethod(10, "foo");

... but test.amethod() tries to impose a checked exception on the caller, so that the caller either has to catch it or propagate it. As the method it's overriding doesn't declare that exception, the overriding method can't either.

As noted in comments, fundamentally you can't override one method with a "more restrictive" one - any call to the original method must still be valid to the override.

From section 8.4.8.3 of the JLS:

More precisely, suppose that B is a class or interface, and A is a superclass or superinterface of B, and a method declaration n in B overrides or hides a method declaration m in A. Then:

  • If n has a throws clause that mentions any checked exception types, then m must have a throws clause, or a compile-time error occurs.
  • For every checked exception type listed in the throws clause of n, that same exception class or one of its supertypes must occur in the erasure (ยง4.6) of the throws clause of m; otherwise, a compile-time error occurs.

people

See more on this question at Stackoverflow