0

If SuperClass declares an exception, then the SubClass can only declare the child exceptions of the exception declared by the SuperClass, but not any other exception, what if I'm declaring checked exception in parent method?

what if I'm declaring checked exception in parent method?

class SuperClass6 { 
// SuperClass doesn't declare any exception 
    void method()throws IOException 
    { 
        System.out.println("SuperClass"); 
    } 
} 

// SuperClass inherited by the SubClass 

class SubClass6 extends SuperClass { 

// method() declaring Unchecked Exception ArithmeticException 


    void method() throws FileNotFoundException
    { 

        // ArithmeticException is of type Unchecked Exception 
        // so the compiler won't give any error 

        System.out.println("SubClass"); 
    } 

    // Driver code 
    public static void main(String args[]) 
    { 
        SuperClass s = new SubClass(); 
        s.method(); 
    } 
 }
Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
  • 5
    What is your question ? – Khalid Shah Mar 30 '19 at 07:20
  • Possible duplicate of [this](https://stackoverflow.com/questions/5875414/why-cant-overriding-methods-throw-exceptions-broader-than-the-overridden-method) – ghoul932 Mar 30 '19 at 07:47
  • Possible duplicate of [Why can't overriding methods throw exceptions broader than the overridden method?](https://stackoverflow.com/questions/5875414/why-cant-overriding-methods-throw-exceptions-broader-than-the-overridden-method) – Progman Mar 30 '19 at 09:33

1 Answers1

1

If you declared a checked exception in parent class method (or an interface) all of the descendents can

  • declare the same exception
  • declare any sub-class of this exception
  • don't declare any exceptions

So, subclasses can't have a broader throws policy, because the calling code may use your objects through parent abstraction and they would be unaware of those.

As to the unchecked exceptions they are basically unregulated at compile time. You are allowed to declare them in throws block as much as you like or throw them without explicit declaration and the calling (or driver as you called it) code will never be forced to handle them.

You can read up more on this Java: checked vs unchecked exception explanation, Why can't overriding methods throw exceptions broader than the overridden method?

Nestor Sokil
  • 2,162
  • 12
  • 28