Home > Uncategorized > Java exception handling

Java exception handling

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.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: