Advertisment

What's new in Java SE aka Project Coin

author-image
CIOL Bureau
Updated On
New Update

Kunal Jaggi, Author of Programming WebSphere MQ with Java and SCWCD Exam Guide with Java EE 5, McGraw-Hill Education

Advertisment

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.

Snapshot

Price:Advanced Java developers

USP: Learn how to simplify your code with the new Java SE 7

Related articles: Java: The Road Ahead http://ld2.in/3sw


Search engine keywords: Java 7

Handle multiple exceptions with a single catch

Advertisment

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

}

Advertisment

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!

tech-news