Java 7 improved try-catch exception handling

7 11 2015

Java 8 with its Coin project introduced convenient exception handling with multi-catch blocks and final rethrows that make exception catching less verbose and more clean.

Multi-catch block

How often you catch two types of Exceptions and need to handle it in two separate catch blocks, even if the handle method does exact the same thing? Like that:

try{
  methodThatThrowsIOException();
  methodThatThrowsFileNotFoundException();
}catch(IOException e){
  System.out.println("Exception occured: " + e.getMessage());
}catch(FileNotFoundException e){
  System.out.println("Exception occured: " + e.getMessage());
}

Since Java 7 you can catch both types in one block with pipe operator:

try{
  methodThatThrowsIOException();
  methodThatThrowsFileNotFoundException();
}catch(IOException | FileNotFoundException e){
  System.out.println("Exception occured: " + e.getMessage());
}

Notice that here the e is of supertype Exception – it is not known at compile time. So you have access only to the Exception class API (not the IOException or FileNotFoundException). If you need type distinction, use the old try-catch API.

Final rethrow

Often times you want to rethrow caught exception to propagate it. Then you use throw mechanism and declare your method signature as throwing certain exception type. Before Java 7 yo could write:

public void myMethod() throws Exception{
  try{
    methodThatThrowsIOException();
    methodThatThrowsFileNotFoundException();
  }catch(Exception e){
    throw e;
  }
}

Notice that in that case you do not know the exception type at compile time, so myMethod() needs to throw the Exception type which is bad practice. The real type is missed in that block. On the other side you can easily notice that the exception types thrown in the try() block are IOException and FileNotFoundException. How to help compiler noticing that? Use keyword final:

public void myMethod() throws IOException, FileNotFoundException{
  try{
    methodThatThrowsIOException();
    methodThatThrowsFileNotFoundException();
  }catch(final Exception e){
    throw e;
  }
}

Now your method is aware of exception types and you can declare what subtypes are thrown.

Advertisements

Actions

Information

Give Your feedback:

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: