Exception Handling with Inheritance

Quick Reference :

  • Unchecked exception can be thrown anywhere in parent and child and there is no issues with that
  • Super class has exception in signature then child class can have subclass of that exception or no exception at all and this is fine
  • Subclass cannot but Exception in it

Types of problems:

There are two types of problems associated with it which are as follows:

  1. Problem 1: If The SuperClass doesn’t declare an exception
    1. Case 1: If SuperClass doesn’t declare any exception and subclass declare checked exception : Compile Time Error
    2. Case 2: If SuperClass doesn’t declare any exception and SubClass declare Unchecked exception : Allowed
  2. Problem 2: If The SuperClass declares an exception
    1. Case 1: If SuperClass declares an exception and SubClass declares exceptions other than the child exception of the SuperClass declared Exception. : Compile time error
    2. Case 2: If SuperClass declares an exception and SubClass declares a child exception of the SuperClass declared Exception. : Allowed
    3. Case 3: If SuperClass declares an exception and SubClass declares without exception. : Allowed

Conclusion

  • If SuperClass does not declare an exception, then the SubClass can only declare unchecked exceptions, but not the checked exceptions.
  • If SuperClass declares an exception, then the SubClass can only declare the same or child exceptions of the exception declared by the SuperClass and any new Runtime Exceptions, just not any new checked exceptions at the same level or higher.
  • If SuperClass declares an exception, then the SubClass can declare without exception.

Leave a Comment