Thursday, July 8, 2010

Catching java.lang.Throwable

Target Audience: Beginners
Can we catch java.lang.Throwable? This is a hot question in java developers world. I would say “yes, you can but you should not”. Is it confusing? Ok. Let me explain

Technically we can catch it as java allows it.

//some code
}catch (Throwable e) {
// TODO: handle exception
The java.lang.Exception and java.lang.Error are only the direct subclasses of java.lang.Throwable. As we know all Exceptions in our code or program should be caught and handled except RuntimeException. RuntimeExceptions are caught and handled some times and most of the time it is let to be thrown to the caller. When RuntimeException is caught and handled? Suppose we are developing a web application and we got a exception while writing to a database and the underlying API like JDBC or Hibernate throws a RuntimeException, then we catch it and show the web user with an appropriate error message. Erros are mostly unrecoverable like java.lang.OutOfMemoryError and ava.lang.StackOverflowError. We can not do anything if we even catch it. So the java world extremely suggest not catch java.lang.Error in other words java.lang.Throwable because if we catch Throwable then we catch Error too.

We can look at in a different view too. Suppose you are creating a API which will be used by other developers ( like an open source component) and your component uses other third party API ( some other open source component like apache beanutils API ). you might have created your component using a specific version( V1.0) of third party component. if a developer try to use your component and pick the wrong version(V.2.0) of the third party component which your component depend on, then he may run into some errors like java.lang.NoSuchMethodError because of different version of third party. So in your component’s code you can plan to catch java.lang.NoSuchMethodError , log it and throw it as your customized Exception saying “ Hello! you are probably using a different version of X API, please use Xv1.0 or any previous versions”. Here we catch the Errors.

So my point is there could be extremely rare situations where you might catch java.lang.Throwable. But much much better to avoid doing so.

Avoid catching java.lang.Throwable and be happy.

A video tutorial explaining very basics of java exception handling

No comments:

Post a Comment