Special Edition Using Enterprise JavaBeans 2.0
EJB Exception Handling
Like other Java APIs, using exceptions to report and handle error conditions is an important part of EJB programming. The distributed and transactional nature of EJB actually makes exception handling more of an issue here than with many other areas of Java development. When a remote client communicates with an EJB component, a lot of things have to happen: a network connection is required, the client must be able to locate the component on some remote server, security permissions must be in place to grant access to the client, the data passed between the two must be correctly marshalled, and so on. Although handled transparently to you (for the most part) as an EJB developer, each of these steps is complex and each has the potential to fail through no fault of your own. In such an environment, exceptions must be planned for and handled correctly because, even though they might not happen often, they are bound to happen sometime. There's no denying that the complexity of a distributed architecture increases the likelihood of some errors. However, the potential problems in a distributed system are in many ways similar to the errors you might encounter when trying to access the local file system or a database from a much simpler application. These are all situations where care must be taken because you're accessing resources outside your local application over which you have little or no control. Where EJB programming differs from simpler applications becomes apparent when you consider transactions, which we covered earlier in Chapter 12. J2EE application servers provide enterprise-strength support for transactional processing, and this support must be present in every aspect of a system built using EJB, including exception handling. As you saw, for a transaction to be valid it must always take the underlying data it manipulates from one consistent state to another. This constraint is not too demanding when everything proceeds in an application as expected. It's when something unexpected happens and an exception results that preserving consistency matters most. Because of this, most of the EJB specifications related to exception handling are directed at the proper ways for the container, the bean provider, and the EJB client to manage a transaction once an exception has occurred. The primary goal of this chapter is to be sure you understand how to handle exceptions in an EJB application. Perhaps most important is learning how transactions are affected when an exception occurs. This includes knowing what the EJB container does for you and knowing for what you're responsible. To get started, you first need to learn how exceptions are classified by the container, because not all exceptions are treated the same. |