一、捕获异常
如果异常出现的话,会立刻终止程序,所以我们要处理异常。
1、在方法中使用try-catch的语句块来处理异常。
对异常的处理:
2.声明异常时,建议声明更为具体的异常,这样可以处理的更具体
1.1 Try
用法:try是try…catch…finally块中用来引导第一部分的关键字,用于声明需要捕获指定语句块的异常
1、如果 try 出现了多个异常对象,那么可以使用多个 catch 来进行异常处理
2、如果 try 中产生了异常,那么就会执行 catch 中的异常处理逻辑,执行完 catch 中的逻辑后会继续执行 try–catch之后的代码
3. 如果 try 中没有产生异常,那么就不会执行 catch 中的异常逻辑,直接执行后续代码
1.2 catch
用来进行某种异常的捕获,实现对捕获到的异常进行处理。
注意:try和catch都不能单独使用,必须连用。
二.finally 关键字:
1、finally 不能单独使用,必须和 try 一起使用
2、finally 一般用于资源释放,无论程序是否出现异常,都要释放资源
import java.io.IOException;
public class Demo01TryCatch {
public static void main(String[] args) {
try {
readFile("D:\\a");
} catch (IOException e) {
// System.out.println("catch 文件后缀发生错误");
// System.out.println(e.toString());//返回 简短的异常消息
// System.out.println(e.getMessage());//返回详细的异常消息包含了异常类型
// System.out.println(e);
e.printStackTrace();
}finally {
System.out.println("一般用来资源释放");
}
System.out.println("后续代码");
}
public static void readFile(String filename) throws IOException {
if (!filename.endsWith(".txt")){
throw new IOException("文件后缀名错误");
}
System.out.println("没有异常");
}
}
三.多个异常如何处理
package Demo01;
import java.util.List;
public class Demo02Exception {
public static void main(String[] args) {
try {
int[] arr1=null;
int[] arr= {1,2,3};
List<Integer> list= List.of(1,2,3);
System.out.println(list.get(3));
}catch(Exception e) {
e.printStackTrace();
}
}
}