Women in Technology

Hear us Roar

  An Exception Handling Framework for J2EE Applications
Subject:   Bad code example
Date:   2006-01-16 23:40:21
From:   sumitaj
You have provided a good approach for handling exception for a J2EE app . But the code example is not good:

CustomerDTO custDTO = null;
//Get customer details
//from local database
return customerDAO

1.Here you are using exceptions for controlling program flow which is a bad programming practice.

2. You add two exceptions to your method signature for handling different error conditions which is a bad approach if the method throws, lets say 5 exceptions.
A better approach would be to add a variable of throwable type to your baseException class and assign the exception to this var.
In the client code you can retrieve this exception and do custom processing using instanceOf .

Like this:

CustomerDAO method:
//throws BaseAppException
public void abc()
throws BaseAppException{
// if not details found
throw new BaseAppException(new CustomerNotActiveException(
"Customer is not active"));

Client method:

//catch CustomerNotActiveException

public void xyz()

}catch(BaseAppException ex){

if (ex().getCause() instanceof CustomerNotActiveException) {.. }

Full Threads Newest First

Showing messages 1 through 1 of 1.

  • Bad code example
    2006-01-16 23:58:26  Shrik [View]

    Using instanceof operator (please refer to Avoid instanceof operator (http://www.javapractices.com/Topic31.cjp) ) itself is a bad practice and you still need to use exception for program flow. In case exception needs to be dealt at any other place other than the Controller itself as mentioned in the example, it's better to make contract clear to the client instead of embedding the cause in the BaseAppException and checking its type. This kind of situation (where you need to handle the exception other than at Controller end) is rare in normal J2EE applications and for those situations I don't think there is any harm in putting the exception explicitely in the throws clause.