How to write exception handling in smart way in java

This tutorial show how you can handle exceptions in smart way. The inputs have been put on the personal experience and on the industry standard. Here we go.

General Rules for handling exception

There are a few basic rules you should follow concerning the handling of exceptions:

• If you can’t handle an exception, don’t catch it. If you are obliged to by the underlying framework, log the error through a Log4j logger, and add a comment that explains why the exception will not be handled.

• Catch an exception as close as possible to its source. Furthermore, you should try to avoid catching the top-level Exception as much as possible. Try instead to catch the specific exception that will actually be thrown. Don’t forget that Runtime Exception is a subclass of Exception, so catching Exception will catch anything that you throw at it.

• In the case of a java web application, if a Runtime Exception or one of its subclasses is thrown and there is nothing you can do to recover from it (ex. the database is not available), you should let the container handle it.

• Almost all Hibernate related database exceptions are subclasses of Runtime Exception. They purposely made it that way because in most situations it is impossible to recover from an exception thrown during a database call. However, in certain cases, such as a constraint violation, you might want to catch a ConstraintViolationException.

Examples of wrongful exception handling

The sections below explain common mistakes often can be done during handle exception in your code. Here is some of points mentioned keep in mind while developing.

Catching RuntimeException

Remember that Runtime Exceptions represent programmatic errors, which are generally unrecoverable bugs in the code. What you seem to be doing here is protecting yourself from a number of error possibilities, though you are not sure which kind. If you need to catch a specific subclass of RuntimeException, such as NumberFormatException or ConcurrentModificationException, then put it in a try-catch that surrounds only the necessary code, and handle it on a case by case basis, instead of covering and entire method such a search function.

Catch-log-throw

The catch-log-throw sequence is a classic antipattern in exception handling. You should either log the exception or throw it but not both. What ends up happening here is the error message is logged twice for the same problem in two different places, making it hard to know where the problem came from in the logs.

Example of catch-log-throw pattern


} catch (Exception e) {
logger.error("Exception in somewhere...." + e);
throw new Exception();
}