Tutorials     About     RSS
Tech and Media Labs

Catching Exceptions

Jakob Jenkov
Last update: 2014-05-26

Somewhere in your application you need to catch and react to thrown exceptions. Typically you will do this towards the top of the call hierarchy.

For instance, in a web application you may catch exceptions in the control servlet (if you have a control servlet).

In a desktop application it may look a bit different, because each listener on the various components, acts as the "top" level of the call hierarchy.

Here is a simple Java catch clause:



} catch(MyAppException e) {


} catch(Throwable t) {


As you can see, there are two catch clauses. One for application specific exceptions, and one for any exceptions that your application has not converted to an application exception. Of course your application should try to convert all exceptions to application specific exceptions, but in case you forget an exception conversion, it is a good idea to have the extra catch clause.

Exception Reactions

In the example shown above, there are only two different reactions:

  • Notifying users.
  • Notifying non users.

In the text Error Causes, Types and Reactions I described two other common reactions to exceptions:

  • Aborting the action.
  • Retrying the action.

However, at the time the exception reaches the top level catch clause, the action should have already been either retried, and / or aborted. Therefore these two common reactions are not visible in the catch clause above.

Notifying Users

How you notify the user depends on what kind of application you are developing.

A web service would notify the "user" (the web service client) by sending a SOAP Fault element.
A Servlet would send an error page back to the user, or an error message embedded in the page.
A desktop application would possibly show an error popup.

Exactly how you notify the users of your application (if any), is up to you to decide.

Notifying Non-users

Non-users are typically notified via the application log. Exactly what kind of severity to log the exception under, depends on the type of exception. Typically, you need to determine the severity of the error before logging it.

For instance, client errors are probably not nearly as severe as some internal, unknown error is. Additionally, a service error may be severe for the functionality of your application, but it may not be necessary to take down your application. Just reboot the external service that failed, and everything works fine again (hopefully).

Jakob Jenkov

Featured Videos

Thread Congestion in Java - Video Tutorial

Sponsored Ads

Maildroppa - Smart Email Marketing Solution
Close TOC

All Trails

Trail TOC

Page TOC