Try Catch Best Practices


When an exception occurs we need to do 2 mains things:

information logging and reporting

This should be combined with exception handling

There are few things that we need to keep in mind when using a try catch block

 

Avoid empty catch block

One of the bad practices in Java is  to have an empty catch block.

In that case When the exception occurs, no statement is executed, and the program fails for unknown reasons.

Basically having a empty catch block means that we ignore the error, and we don’t even want to log the exception in order to solve it sooner or later.

Even if in some case, we know that the exception is not a defect that need to be fixed, we should at least log the error message.

 

try(
      // some code

}catch (Exception ex) {

      // we don’t care
}

 

The code should be prepared to deal with any type of exception. 

 

Avoid Catching the generic Exception class

The main reason that leads a developer to use the generic Exception class is to simplify the code.

But is this a good idea? Of course not.

 

Catching all exceptions

In some code blocks, it can happen that many Exception types could potentially be thrown. And the first idea that comes to our mind is to declare the throws Exception rather than the different exceptions that could be thrown.

All the Exception are subclasses of Exception class, which means the generic catch (Exception e) catches all subclasses: RuntimeException, NullPointerException, IndexOutOfBoundsException, ArrayStoreException

Therefore, we are catching some exceptions that are different from the expected ones, which is obviously a risky situation.

 

Logging exceptions

When using catch (Exception e), we lose the information about the original failure reason. The message that we get is a generic one

Avoid Using printstacktrace 

Why  exception.printStackTrace() is a bad practice ?

  • for security reasons: it can happen that a stack trace is displayed to an end-user. This is dangerous because the message can contain some information about the application, data server name ….
  • It’s a bad user experience if the stack trace is displayed to an end-user
  • printStackTrace() prints to a console. This means that a developer should check the log files and the server console, which makes the monitoring more difficult. We should pass this information to a logger.
  • In server applications the stacktrace blows up your stdout/stderr file. It may become larger and larger

 

Finally and catch

If you’re using JDK 7+, you should simply use try-with-resources statement instead of the finally block .

In some particular cases, a finally block will still be needed, even in JDK 7+ when a resource doesn’t implement AutoCloseable

So Prior to Java SE 7, you need to use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly

 

static void writetoFile(Path path) throws IOException {

    List<String> fruits = (List<String>) Arrays.asList(

      "apple", "kiwi", "annanas", "orange"

    );

      ObjectOutputStream output = new ObjectOutputStream(Files.newOutputStream(path));

    try {

      output.writeObject(fruits);

    }finally{

    if (output != null) output.close();

    }

}

 

By using The try-with-resources Statement, the code becomes simpler

 

static void writetoFile_(Path path) throws IOException {

    List<String> fruits = (List<String>) Arrays.asList(

      "apple", "kiwi", "annanas", "orange"

    );

    try (

        ObjectOutputStream output = new ObjectOutputStream(Files.newOutputStream(path));

    ){

      output.writeObject(fruits);

    }

}

 

 

Recent Posts