ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

An Exception Handling Framework for J2EE Applications
Pages: 1, 2, 3, 4, 5, 6

Here is a sample of throwing a checked exception.



public void updateUser(UserDTO userDTO) 
  throws BaseAppException{
    UserDAO userDAO = new UserDAO();
    UserDAO.updateUser(userDTO);
    ...
    if(...)
        throw new RegionNotActiveException(
            "Selected region is not active");
}

Controller Method:
...
try{
    User user = new User();
    user.updateUser(userDTO);
}catch(BaseAppException ex){
    //ExceptionHandler is used to handle
    //all exceptions derived from BaseAppException
}
...

So far we have discussed that all methods that could potentially throw checked exceptions and are called by Controller should contain only BaseAppException in their throws clauses. However, this actually implies that we can't have any other application exception in the throws clause. But what if you need to perform some business logic based on a certain type of exception in the catch block? For handling those cases, a method may also throw a specific exception. Keep in mind that this is a special case and should not be taken for granted by developers. The application exception in question again should extend the BaseAppException. Here is an example:

CustomerDAO method:
//throws CustomerNotActiveException along with
//BaseAppException
public CustomerDTO getCustomer(InputDTO inputDTO)
    throws BaseAppException,
        CustomerNotActiveException {
    . . .
    //Make a DB call to fetch the customer 
    //details based on inputDTO
    . . .
    // if not details found
    throw new CustomerNotActiveException(
        "Customer is not active");
}

Client method:

//catch CustomerNotActiveException
//and continues its processing
public CustomerDTO getCustomerDetails(
  UserDTO userDTO)
    throws BaseAppException{
    ...
    CustomerDTO custDTO = null;
    try{
        //Get customer details 
        //from local database
        customerDAO.getCustomerFromLocalDB();
    }catch(CustomerNotActiveException){
        ...
        return customerDAO
            .activateCustomerDetails();
    }
}

Handle unchecked exceptions at the web application level

All unchecked exceptions should be handled at the web application level. A web page can be configured in web.xml to be displayed to the end user whenever any unchecked exception occurs in the application.

Pages: 1, 2, 3, 4, 5, 6

Next Pagearrow