Java 7 ile birlikte catch bloğunda birden fazla Exception yakalanabilmektedir. Eski yöntemde aşağıdaki gibi olacaktır :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MultiCatchException {
public static void main(String[] args) {
try {
File f1 = new File("c:\\date.txt");
FileReader fis = new FileReader(f1);
BufferedReader reader = new BufferedReader(fis);
String line = reader.readLine();
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyy");
Date date = format.parse(line);
System.out.println("dosyadaki date okundu");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Örnek FileNotFoundException ve IOException fırlatmasından dolayı ayrı ayrı catch bloğu yazılmıştır. ParseException içinde catch bloğu eklenmiştir. Java 7 ile birlikte aşağıdaki gibi aynı örnek yazılabilir :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MultiCatchException {
public static void main(String[] args) {
try {
File f1 = new File("c:\\date.txt");
FileReader fis = new FileReader(f1);
BufferedReader reader = new BufferedReader(fis);
String line = reader.readLine();
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyy");
Date date = format.parse(line);
System.out.println("dosyadaki date okundu");
}catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
FileNotFoundException zaten bir IOException olmasından dolayı yazılmasına gerek yoktur. Exception'lar aralarına pine (|) işareti koyularak ayrılmıştır. Görüldüğü birden fazla catch kullanılmamıştır.