Java - 异常
11.认识异常.pdf
用 try catch 处理异常需要注意的问题:
-
catch块当中,一定要捕获相应的异常,如果程序抛出的异常在catch块当中,不能被捕获。那么就会交给JVM处理。
-
可以通过 catch 来捕获多个异常。
int[] arr = new int[]{1,2,3};
arr = null;
//1.
try {
System.out.println(arr[4]);
} catch (ArrayIndexOutOfBoundsException | NullPointerException e){
e.printStackTrace();
System.out.println("访问数组越界了或访问了空引用!");
}
//2.
int[] arr = new int[]{1,2,3};
arr = null;
try {
System.out.println(arr[4]);
} catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
System.out.println("访问数组越界了!");
} catch (NullPointerException e){
e.printStackTrace();
System.out.println("访问空引用了!");
}
-
不建议直接捕获 Exception。
-
finally 块当中的代码,终究会被执行的。通常将释放资源的代码块放到 finally语句里。
public static int func(){
int[] arr = new int[]{1,2,3};
try {
System.out.println(arr[4]);
return 0;
} catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
System.out.println("这是异常处理块");
return 1;
} finally {
System.out.println("这是finally语句块");
return 2;
}
}
public static void main(String[] args) {
System.out.println(func());
}

- 不建议在finally 当中出现 return 语句。
throws 异常处理

注意事项和使用细节:
自定义异常

throws 和 throw 区别




浙公网安备 33010602011771号