认识异常
1.除以0
public static void main(String[] args) {
System.out.println(10/0);
}
2.数组下标越界
public static void main(String[] args) {
int[] arr = new int[]{1,2,3};
System.out.println(arr[4]);
}
3.访问null(空指针异常)
public static void main(String[] args) {
String a = null;
System.out.println(a.length());
}
防御式编程
1.LBYL(LOOK BEFORE YOU LEAP):在操作之前做好检查
2.EBFP(IT IS EASIER TO ASK FORGIVENESS THAN PERMISSION):先操作,遇到问题在解决。
捕获异常
1.try…catch…用法
public static void main(String[] args) {
try {
String a = null;
System.out.println(a.length());
}catch (NullPointerException e){
System.out.println("空指针异常");
e.printStackTrace();
}
}
2.注意以下用法
①.当try中有多个异常,仅执行最先捕获异常的Catch语句块并执行
public static void main(String[] args) {
try {
int []arr = new int[]{1,2,3,4};
System.out.println(arr[6]);
String a = null;
System.out.println(a.length());
}catch (NullPointerException e){
System.out.println("空指针异常");
e.printStackTrace();
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("越界异常");
e.printStackTrace();
}
}
②同样当catch捕获到try中异常,该异常后的命令不在执行
public static void main(String[] args) {
try {
int []arr = new int[]{1,2,3,4};
System.out.println(arr[6]);
System.out.println("执行此打印");
System.out.println(" ============");
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("越界异常");
e.printStackTrace();
}
System.out.println("结束");
}
③同一个catch可以捕获多个异常(从以下代码块结果来看,捕捉顺序与①相同
public static void main(String[] args) {
try {
int[] arr = new int[]{1, 2, 3, 4};
System.out.println(arr[6]);
String a = null;
System.out.println(a.length());
} catch (NullPointerException | ArrayIndexOutOfBoundsException e) {
System.out.println("空指针异常或者超出异常");
e.printStackTrace();
}
}
也可使用
public static void main(String[] args) {
try {
String a = null;
System.out.println(a.length());
} catch (Exception e) {
System.out.println("异常捕捉");
e.printStackTrace();
}
}
finally使用注意事项(finally所起的作用就是释放资源,但是如果try和finally都有return,此时会执行Finally中return.
public static void main(String[] args) {
int size = 4;
int rem = num(size);
System.out.println(rem);
}
public static int num(int size) {
try {
return size;
} catch (Exception e) {
System.out.println("异常捕捉");
e.printStackTrace();
}finally {
return 20;
}
}