异常捕捉try catch的使用
package com.jl.learning.exception;
//try catch的使用
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ExceptionTest2 {
public static void main(String[] args) {
/*try {
FileInputStream fis = new FileInputStream("C:\\Users\\Adinistrator\\Java\\新建文本文档.txt");
System.out.println("以上若出现异常,这里不运行!");
} catch(FileNotFoundException e){
System.out.println("文件不存在!");
}*/
/*try {
FileInputStream fis = new FileInputStream("C:\\Users\\Adinistrator\\Java\\新建文本文档.txt");
} catch(IOException e){//抛出FileNotFoundException异常的父类异常IOException,多态!
System.out.println("文件不存在!");
}*/
try {
//创建输入流
FileInputStream fis = new FileInputStream("C:\\Users\\Adinistrator\\Java\\新建文本文档.txt");
//读取文件
fis.read();//这里read()也会抛出异常
} catch(FileNotFoundException e){//抛出FileNotFoundException异常的父类异常IOException,多态!
System.out.println("文件不存在!");
} catch (IOException e){//抛出异常得从小到大,不能从大到小catch (FileNotFoundException e)和catch (IOException e)不能交换位置
//因为先捕捉IOException的时候,包含了FileNotFoundException,再处理FileNotFoundException会报错已经处理过FileNotFoundException
System.out.println("读文件报错了!");
}
System.out.println("=========================================");
try {
//创建输入流
FileInputStream fis = new FileInputStream("C:\\Users\\Adinistrator\\Java\\新建文本文档.txt");
//进行数学运算
System.out.println(100 / 0);//运行时异常,编写时可以处理也可以不处理
} catch(FileNotFoundException| ArithmeticException|NullPointerException e){//JDK 8 后允许多个异常同时写,用|隔开
System.out.println("文件不存在?数学异常?空指针异常?都有可能!");}
}
}