Thursday, September 30, 2010

Intelligent Catch Block

A new Feature in jdk1.7....
Use just one catch instead of two unless needed.......

Suppose you are writing a program that interact with SQL and do some IO,suppose your program can throw SQLException and IOException...
Now you know that,you have to keep separate catch Blocks to catch the Exception thrown by the different hierarchy Classes as in our case IOException and SQL Exception...

so we have to write
try
{
//some code that can throw IO or SQL Exception
}
catch(IOException e)
{
//so some work
}
catch(Exception e)
{
//do same work
}

as we can see we have to perform the same task independent of the Exception type,but still we have to keep two catch blocks ..that is the code is lengthy as well as redundant.....
so to solve this problem sun came with a solution and the solution is just a Operator Yes...the same old bitwise OR operator(|)...

now we can catch the Exceptions in one catch block using Bitwise OR operator...
so we will say::

try
{
//some code that can throw IO or SQL Exception
}
catch(final IOException | SQLException e)
{
//handle the ecxeption
}

Caution::but keep in mind....that 'e' must be final.........

0 comments:

Post a Comment