Amajor part of developing Java applications is handling error conditions, and Struts applications are no exception to that rule. Like most other such applications, Struts bases its error handling around Java's exception-handling mechanism. However, as of version 1.1, Struts supports a powerful exception-handling mechanism called declarative exception handling. Declarative exception handling is a mechanism that lets you specify how an exception should be handled, but without having to include the handler within your application's Java code. Instead, the exception handler is declared in the Struts configuration file (e.g., struts-config.xml). Declarative exception handling enables you to change how exceptions are handled without having to recompile your application's code. You simply update the Struts configuration file and restart the application. This is a significant advantage.
Prior to version 1.1, exception handling in Struts applications functioned much the same way as it does in most other applications. Inside your code, you had to have several try-catch blocks to handle each of the exceptions that could be thrown. While this solution works and is effective, there is often a great deal of overlap between different parts (e.g., Action classes) of a Struts application that have to implement the same exception processing logic. For instance, if two Action classes interface with the same business service and that service throws a custom business exception, each class would have to implement logic to handle the exception being thrown when something goes awry. Now, imagine that you have 20 or 30 Action classes that use a service (or set of services) that could throw a custom business exception. There would be a great deal of exception-handling logic duplicated across those Action classes. Struts' declarative exception-handling mechanism allows you to create a common exception handler that can be reused by all of those actions. This centralizes all of the exception-handling logic in one place and reduces the duplication of code.
This chapter illustrates how to configure and use Struts' built-in exception handler and provides instructions for creating your own custom exception handler. Finally, this chapter steps through the process of updating the Mini HR application to take advantage of declarative exception handling.