9. 异常处理
Error
是程序无法处理的错误,出现时线程被JVM终止。
Exception
,指的是程序运行时可以处理的异常。其继承关系如下表:
运行时异常&非运行时异常
- 运行时异常
都是RuntimeException
类及其子类异常,如NullPointerException
、IndexOutOfBoundsException
等, 这些异常是非检查型异常,程序中可以选择捕获处理,也可以不处理。*
- 非运行时异常
RuntimeException
以外的异常,类型上都属于Exception
类及其子类。从程序语法角度讲是必须进行处理的异常,如果不处理,程序就不能编译通过。如IOException
、SQLException
等以及用户自定义的Exception
异常,这些是检查型异常。
内置异常方法
捕获异常
采用try-catch
语句进行异常的捕获。
说明:
finally
里的语句无论如何肯定会执行try-catch
外的语句可能因为return
而不执行
public static void foo1(){
int[] arr = new int[5];
for(int i = 0; i < 5; i ++)
arr[i] = i;
//把第k个元素的值除以x
Scanner sc = new Scanner(System.in);
int k = sc.nextInt();
int x = sc.nextInt();
try {
arr[k] /= x;
}
catch(ArithmeticException e){
System.out.println("除0异常");
return;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组越界");
}
finally {
for(int i = 0; i < 5; i ++)
System.out.println(arr[i]);
}
//若是除0异常可能因为return语句导致下面的语句不被执行
System.out.println("程序执行结束");
}
抛出异常
throw
:在函数内抛出一个异常throws
:在函数的定义时抛出可能的异常
检查型的异常必须被抛出。
例子如下:
public static void foo2() throws IOException, NoSuchFieldException {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
if (x == 1) {
throw new IOException("找不到文件");
}
else
{
throw new NoSuchFieldException("自定义异常");
}
}
try-with-resources语法糖
类似于python的with
语句,Java也有文件相关的异常处理自动化的语法,防止出现异常时文件资源未关闭造成资源的浪费。
语法:try(打开的资源){}-catch
例子如下,还能从这里参考如何进行简单的文件读取操作:
public static void foo3()
{
String line;
try(
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
)
{
while((line = br.readLine())!= null)
{
System.out.println("Line => " + line);
bw.write("Copy =>: " + line + "\n");
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}