Java rethrow an exception

The exception we caught in catch block will be throw again from catch block is called rethrow exception. We can rethrow exception two ways.

  1. Re-throw an exception we caught
  2. Re-throw wrapped exception

The purpose of the rethrow operation is to propagate the exception to the higher level, But before propagation we would perform some activities like logging, send an email, audit error, rollback transaction … etc. We can perform such activities in the catch block and re-throw the exception again. In this way, a higher level gets notified that the exception has occurred in the application.

Example 01 : Re-throw an exception we caught

Output :

main begin
processing fullName …
Unable to Process Name !!!
main end

In the above example, we are rethrowing exception we caught, before rethrowing we are logging the error. But we can also do auditing error or send email or what ever we want before rethrowing.

Example 02 : Re-throw wrapped exception

Output :

main begin
processing fullName …
unable to evaluate fullname
Unable to Process Name !!!
main end

In the above example, we caught exception and encapsulate that into IllegalArgumentException and then rethrown. Here we are encapsulating caught exception into pre-defined exception. But we can also encapsulate into user defined exception.

Scroll to Top