DEV Community

Cover image for Chained Exceptions
Paul Ngugi
Paul Ngugi

Posted on

Chained Exceptions

Throwing an exception along with another exception forms a chained exception. The catch block rethrows the original exception. Sometimes, you may need to throw a new exception (with additional information) along with the original exception. This is called chained exceptions. The program below illustrates how to create and throw chained exceptions.

Image description

The main method invokes method1 (line 7), method1 invokes method2 (line 16), and method2 throws an exception (line 24). This exception is caught in the catch block in method1 and is wrapped in a new exception in line 19. The new exception is thrown and caught in the catch block in the main method in line 9. The sample output shows the output from the printStackTrace() method in line 10. The new exception thrown from method1 is displayed first, followed by the original exception thrown from method2.

Top comments (0)