多重捕获:
try {
//可能会发生异常的语句
} catch (FileNotFoundException e) {
//调用方法methodA处理
} catch (IOException e){
//调用方法methodA处理
} catch (ParseException e){
//调用方法methodA处理
}
Java 7之后的多重捕获的格式:
//多重捕获格式
try {
//可能会发生异常的语句
} catch (IOException | ParseException e) {
//调用方法methodA处理
}
代码示例
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TryCatchCatchs {
public static void main(String[] args) {
Date date = readDate();
System.out.println("日期 = " + date);
}
private static Date readDate() {
//IO文件输入流
FileInputStream readfile = null;
//IO文件输出流
InputStreamReader ir = null;
BufferedReader in= null;
try {
//通过FileInputStream读取一个文件文件
readfile = new FileInputStream("readme.txt");
ir = new InputStreamReader(readfile);
in = new BufferedReader(ir);
//读取文件中的一行数据
String str = in.readLine();
if(str == null){
return null;
}
//初始化时间格式
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//格式化时间格式
Date date = df.parse(str);
return date;
} catch (IOException | ParseException e) {
System.out.println("处理多捕获异常...");
e.printStackTrace();
}
return null;
}
}