Skip to content
Advertisement

How to show that a Catch block for the Parent-exception will handle subclasses as well

I have met this problem.

I have created a class CatHandler, with 3 inner classes (ExceptionAlpha extends Exception, ExceptionBeta extends ExceptionAlpha, ExceptionGammer extends ExceptionBeta). These three exception subclasses are empty; they contain no code. All code should be written in CatHandler.

Now the question is to write some code in CatHandler to show that ExceptionBeta and ExceptionGammer will be caught in the catch block of type ExceptionAlpha?

For the output, we can use System.err.println(), getMessage() and printStackTrace() and other appropriate print statements to show that the exception subclasses have been successfully caught.

I’m wondered how to show that exception handling happens in such a way? It is really confusing.

JavaScript

Advertisement

Answer

the question is to write some code in CatHandler to show that ExceptionBeta and ExceptionGammer will be caught in the catch block of type ExceptionAlpha.

First, you need to declare a few methods that will throw ExceptionBeta and ExceptionGamma.

Because both of them are checked exceptions, you should include a throws clause in the method declarations.

It’s better to define all the nested classes as static, otherwise these exceptions will always require an object enclosing class (i.e. CatHandler) in order to be instantiated.

The code in the main() invokes the unsafe behavior and handless it with catch blocks expecting ExceptionAlpha or its subtypes.

To demonstrate the actual type of a caught exception, we can extract the class name from its Class object or print stack trace (class name will mentioned at the very beginning a stack trace). Both options are shown below.

JavaScript

Output

JavaScript
Advertisement