Handling Exceptions in Inherited Methods

This program demonstrates handling exceptions in inherited methods.

Problem Statement

Write a Java program where a subclass overrides a method and handles exceptions differently.

Source Code

1 class Base {
2 void risky() throws Exception {
3 throw new Exception("Eduinq Base Exception");
4 }
5 }
6 class Derived extends Base {
7 void risky() {
8 try {
9 super.risky();
10 } catch(Exception e) {
11 System.out.println("Eduinq Derived Handling: "+e.getMessage());
12 }
13 }
14 }
15 public class InheritanceExceptionExample {
16 public static void main(String[] args) {
17 System.out.println("Eduinq Inheritance Exception Example");
18 Derived d=new Derived();
19 d.risky();
20 }
21 }

Program Output

					Eduinq Inheritance Exception Example
Eduinq Derived Handling: Eduinq Base Exception
				

Explanation

Subclasses can override methods and handle exceptions differently. - Base class declares exception, subclass provides custom handling. - Improves flexibility and error management. - In enterprise systems, inheritance exception handling ensures extensibility. Conclusion: Shows handling exceptions in inheritance.

Quick Links to Explore