java中的异常捕捉和python的很相似,catch里面的错误一般都会写到日志中,而不是程序因为一些意外原因报错而让其停止运行,而是捕捉到放到日志中去查询
// 什么是包装类: 一些变量原来没有对应的方法来操作他们,所以要搞一些方法来操作他们,而管理这些方法的类叫做包装类
import java.lang.reflect.Array;
import java.util.*;
public class Demo14Class {
public static void main(String[] args) {
// 捕捉异常
System.out.println("捕捉异常==================");
try {
int[] intList1 = {1,2,3,4};
int int1 = 4;
tryCatch(intList1, int1);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("进去异常执行了");
System.out.println(e.toString());
System.out.println(e.getMessage());
} finally {
System.out.println("不管是否异常我都会执行!");
}
}
public static void tryCatch(int[] list1, int num1) {
int num2 = list1[num1];
System.out.println(num2);
}
}
执行结果:
捕捉异常==================
进去异常执行了
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
Index 4 out of bounds for length 4
不管是否异常我都会执行!