Kunal Jaggi, Author of Programming WebSphere MQ with Java and SCWCD Exam Guide with Java EE 5, McGraw-Hill Education
BANGALORE, INDIA: Project Coin, a Java Community Process (JCP) backed JSR 334 initiative is an effort to make the Java programming language more friendly, productive and easy to code. JSR 334 introduces a few small, but highly useful, language features which are now an integral part of Java SE 7. The significance of JSR 334 is rare in a way because this is the first core Java programming language changes since JDK 5 (project Tiger) was released in 2004. This article is the first in a series of two articles aimed at familiarizing you with some of these language features.
|
Handle multiple exceptions with a single catch
If you have used the Java programming language, you might have encountered several scenarios where you need to wrap a method call or a group of statements with a few catch blocks, each block catching a specific exception type (and implicitly its subtype). For example, consider the following code snippet presented in Listing 1 which reads a database row with JDBC calls and writes it into a file on the disk.
Listing 1
BufferedWriter writer = null;
Statement stmt= null;
try
{
writer = new BufferedWriter ( new OutputStreamWriter( fos ));
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SELECT_EMPLOYEE);
while ( rs.next() ){
writer.write(rs.getString("EMP_NAME"));
}
}
catch(SQLException ex)
{
Logger.log("Error occurred : "+ ex.getMessage());
//do something with the exception
}
catch ( IOException ex)
{
Logger.log("Error occurred : "+ex.getMessage());
//do something with the exception
}
The above code is cluttered with multiple catch blocks, thus making it difficult to read. Also, we have a common code such as log statement and exception handling code in each catch block, resulting in duplication of codes. One option is to move the exception handling code to a separate method call; still we need to call the method from each catch block. Thanks to JDK 7, we can now combine a series of exception types in a single catch block, separated by the “OR” operator symbol “|”. This is presented in Listing 2 below.
Listing 2
try
{
// Open a writer
// Create a Statement and open ResultSet
// Access the ResultSet
}
catch(SQLException | IOException ex)
{
Logger.log("Error occured : "+ ex.getMessage());
//do something with the exception
}
Click here to continue reading!