In Java, the super keyword is used to refer to the immediate parent class of a subclass. When it comes to exception handling, super can be used to explicitly call a superclass method that might throw an exception. The subclass must either handle or propagate that exception.
This approach is useful when:
- A subclass wants to reuse exception-handling logic from its parent.
- The base method contains critical operations that may throw checked exceptions.
Important Aspects
| Aspect | Description |
|---|---|
super.method() |
Calls the superclass method that may throw an exception. |
| Handling required | If the superclass method throws a checked exception, the subclass must handle it using a try-catch block or declare it using throws. |
| Optional for unchecked | If the exception is unchecked, no need to catch or declare it explicitly. |
Example Program: Using super to Handle Exceptions
import java.io.IOException;
// Base class
class Developer {
public void develop() throws IOException {
System.out.println("Developer is writing code...");
throw new IOException("Compilation failed!");
}
}
// Subclass using super to call and handle parent exception
class JuniorDeveloper extends Developer {
@Override
public void develop() {
try {
super.develop(); // Call to superclass method
} catch (IOException e) {
System.out.println("Handled in JuniorDeveloper: " + e.getMessage());
}
}
}
// Subclass choosing to propagate exception
class SeniorDeveloper extends Developer {
@Override
public void develop() throws IOException {
super.develop(); // No try-catch, exception propagated
}
}
public class SuperExceptionDemo {
public static void main(String[] args) {
Developer dev1 = new JuniorDeveloper();
dev1.develop(); // Exception is handled internally
Developer dev2 = new SeniorDeveloper();
try {
dev2.develop(); // Exception must be caught here
} catch (IOException e) {
System.out.println("Handled in main: " + e.getMessage());
}
}
}
/*
Developer is writing code...
Handled in JuniorDeveloper: Compilation failed!
Developer is writing code...
Handled in main: Compilation failed!
*/Using super with exception handling allows subclasses to:
- Reuse and handle exceptions from parent methods.
- Choose whether to handle or propagate exceptions further.
This enables structured and layered exception management, making code modular, maintainable, and readable.
