Blog Archive

Saturday, 28 December 2013

Java 7 – Try statement with multi catch

In this tutorial we are going to see java7 multi catch for similar type exception
Historically, catching multiple exceptions results in a catch block for each exception, with each block containing a variable with the type of that particular exception. In many cases, these catch blocks contained identical code that referenced the specified exception variable. It was difficult to write a common method to handle this duplicated code because the exception variables had different types, So you have possibility to write code to catch parent  exception to avoid duplicated code, but it is not always suitable way.Java lets you to catch multiple exceptions in single catch block
Old Catch Bock
package com.javatutorialscorner.java7.trycatch;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class OldTryCatch {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = "";
File file = null;
BufferedReader br = null;

file = new File(path);
try {
br = new BufferedReader(new FileReader(file));
System.out.println(br.readLine());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

Java7 Catch

package com.javatutorialscorner.java7.trycatch;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;

public class NewtryCatch {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = "";
File file = null;
BufferedReader br = null;

file = new File(path);

try {
br = new BufferedReader(new FileReader(file));
System.out.println(br.readLine());
/*some jdbc code */
} catch (IOException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}


}

In Java7 catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).

Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.

Bytecode generated by compiling a catch block that handles multiple exception types will be smaller than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.

0 comments

Post a Comment