Archive

Archive for February, 2010

Java exception handling – part 2 – what does IBM say?

17.02.2010 Leave a comment

Quick search led to finding official recommendations for exception handling in EJB, straight from IBM. Here they are:

  • Use a logging framework, such as Log4J
  • Business  logic errors should be reported as checked exceptions
  • System exceptions (from DB, JNDI etc.) should be thrown as unchecked exceptions

They also offer some information about how the exceptions are handled by the EJB container.

Advertisements
Categories: Uncategorized

Java exception handling

08.02.2010 Leave a comment

Recently I participated in a training and workshop on Test Driven Development by Sami Hokonen. Sami criticized the default error hadling template in Eclipse:

void myMethod(){
    try {
        ...
        methodThrowingSomeException();
        ...
    } (catch SomeException e) {
        e.printStackTrace();
    }
}

According to Sami, problems with that approach are:

  1. Console is usually invisible when running a desktop application.
  2. And because of that error is ignored.

He proposed a different approach:

void myMethod(){
    try {
        ...
        methodThrowingSomeException();
        ...
    } (catch SomeException e) {
        throw new RuntimeException(e);
    }
}

Benefits:

  1. Clean code.
  2. Application exits with the error message indicating what happened.

Lack of try/catch blocks certainly makes the code easier to read. I do have an issue with the second statement. Throwing unchecked exception all over the place is reckless and leads to frequent crashes of the application. That might make sense in GUI applications, as the user sees an error message and can quickly restart app. Does it make sense on server side? Standard output gets redirected to a file, so the error is recorded (at least for a while).  Additionally, checked exception can encourage thinking about error conditions and dealing with them in a meaningful way.  This seems to be the reason why Java still has them – it is mostly used in server side for enterprise-class systems. Along those lines, I would propose this:

void myMethod() throws SomeException{
    ...
    methodThrowingSomeException();
    ...
}

And,  somewhere else:

void majorOperation() {
    try{
        ...
        myMethod();
        ...
    } (catch Exception e) {
        log(LoggingLevel.error, "Exception in majorOperation");
        log(e);
    }
}

In summary: throw an exception untli you can do something meaningfull about it. That way, you can see all the things which can go wrong in the code.

Homework: how does WebSphere behaves if you throw a RuntimeException from your EJB?  This looks helpful.

Categories: Uncategorized