St.Antario
St.Antario

Reputation: 27385

Java exceptions and throw clauses

The JLS in its 8.4.8.3 clause mentioned about overriding methods containing throws clause, but it's not exactly clear what they were trying to say by this:

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

  • If m2 has a throws clause that mentions any checked exception types, then m1 must have a throws clause, or a compile-time error occurs.

What type of checked exception m2 should throw in its throws clause?

Upvotes: 1

Views: 104

Answers (3)

Neeraj Jain
Neeraj Jain

Reputation: 7730

What type of checked exception m2 should throw in its throws clause?

m2 can only throws all or a subset of the exception classes in the throws clause of the overridden method in the superclass.

for Example :

class Base                     
{
    void amethod() { }
}

class Derv extends Base
{
    void amethod() throws Exception { } //compile-time error
}

Upvotes: 0

nhaarman
nhaarman

Reputation: 100388

The example in code:

class B implements A {

  @Override
  void m() throws SomeException {
    /* ... */
  }
}

What is not allowed:

interface A {

  void m(); // This is not allowed
}

What is allowed:

interface A {

  void m() throws SomeException;
}

Or even:

interface A {

  void m() throws Exception;
}

Edit:

The second bullet point from your quote:

  • For every checked exception type listed in the throws clause of m2, that same exception class or one of its supertypes must occur in the erasure (§4.6) of the throws clause of m1; otherwise, a compile-time error occurs.

Upvotes: 3

SMA
SMA

Reputation: 37023

It says that, if your child class throws checked exception which parent doesnt then it will lead to compile time error.

Consider this:

class A {
    public void testMethod() {}
}

class B extends A {
    public void testMethod() throws FilNotFoundException {}
}

This will throw a compile time error. Further it says, to resolve this, you may need parent's method to throw FileNotFoundException.

Upvotes: 1

Related Questions