New Features in Try/Catch – JDK 7

27 / Aug / 2012 by Robin 0 comments

In our applications we generally make use of try-catch blocks to handle exceptions. Since JDK-7 , It has certain new features. These features are quite good , I must say.

Some of the new changes in try/catch bloack are :

1.  Multiple exceptions handling in only one catch block.
2.  Finally out of scope. (Try-Catch with resources is new feature.)

1. Catching Multiple Exception Types

In our applications , We generally make use of catch block like these :-

[java]
catch (SQLException ex) {
logger.log(ex);
throw ex;
catch (IOException ex) {
logger.log(ex);
throw ex;
}
[/java]

We can cleary see that we are maintaining duplicate code for handling exceptions . So , In Java SE 7 there are some modifications that resolves this issue.

Have a look at following snippet of code :-

[java]
catch (IOException | SQLException ex) {
logger.log(ex);
throw ex;
}
[/java]

Here above , We can see that a single catch block is handling multiple exceptions. Isn’t it cool. 🙂

For more details , Please visit Oracle-docs for try-catch

2. Finally out of scope. (Try-Catch with resources is new feature.)

We generally make use of finally block to close thre resources we used in our code.
e.g.

[java]
String readLineFromBlock(String pathOfFile)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(pathOfFile));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
[/java]

You can see that in above written snippet of code, We are closing the reader and handling the exception for the same , But In JDK7, finally is no longer required. Now in JDK-7 a new feature is added that is , Try-Catch with resources . This is a wonderful feature .

Just have a look at the syntax :

[java]
String readLineFromBlock(String pathOfFile) throws IOException {
try (BufferedReader br =new BufferedReader(new FileReader(pathOfFile))) {
return br.readLine();
}
}
[/java]

You can see that in above written snippet of code, We are not closing the reader and handling the exception for the same , It is being taken care of automatically by JDK-7.

Now closing the streams , readers n all will not be a headache for you , Need not to to write a extra snippet of code for them & then enclosing them again in try-catch block.

For more details , Please visit try-catch resource

These are really good features, Quite helpful . Just give a try . 🙂

Thanks & Regards,
Robin Sharma,

robin@intelligrape.com,
Intelligrape Software Services.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *