Pages

Wednesday, November 27, 2013

Java 7 Tutorial - Catching Multiple Exceptions

Java 7 allows catching multiple exceptions in the single catch block.
Prior to Java 7 if a method can create multiple exceptions then each
exception has to be handled seperatly.

So it must be
try
{
}
catch(IOException 1)
{
handleException(1);
}
catch(ParseException 2)
{
handleException(2)
}

This will lead to duplicate code in each catch block. Now with SE7 this can be
avoided and it can be handled in the same catch block.

package com.ravi.java7learning;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class SampleExceptionHandler {

public static void main(String a[])
{
try {
FileWriter writer = new FileWriter(new File("c:\\tutorial\\HelloWorld.txt"));
SimpleDateFormat format = new SimpleDateFormat();
Date parsedDate = format.parse("07/10/96 4:5 PM, PDT");
writer.write("HelloWorld");
writer.flush();
writer.close();
} catch (IOException | ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

1 comment:

 
Blogger Templates