Java异常
- 前言:一个健壮的程序必须处理各种各样的错误。所谓错误,就是程序调用某个函数的时候,如果失败了,就表示出错。调用方获取调用失败信息,一般有两种方法
方法一:约定返回错误码(C++管用手法)
int code = processFile("C:\\test.txt");
if (code == 0) {
// ok:
} else {
// error:
switch (code) {
case 1:
// file not found:
case 2:
// no read permission:
default:
// unknown error:
}
}
方法二:在语言层面上提供一个异常处理机制(Java常用)
1. Java内置了一套异常处理机制,总是使用异常来表示错误。
2. 经常一些Java的操作没有及时做出异常处理时,编译器会报错
try {
String s = processFile(“C:\\test.txt”);
// ok:
} catch (FileNotFoundException e) {
// file not found:
} catch (SecurityException e) {
// no read permission:
} catch (IOException e) {
// io error:
} catch (Exception e) {
// other error:
}
- 继承关系图
- 从继承关系可以看出,
Throwable是异常体系的根,它继承自Object。Throwable有两个体系:Error和Exception,Error表示严重的错误,程序对此一般无能为力,例如:
- ==
OutOfMemoryError==:内存耗尽
- ==
NoClassDefFoundError==:无法加载某个Class
- ==
StackOverflowError==:栈溢出
- 而
Exception则是运行时的错误,它可以被捕获并处理。某些异常是应用程序逻辑处理的一部分,应该捕获并处理。例如:
- ==
NumberFormatException==:数值类型的格式错误
- ==
FileNotFoundException==:未找到文件
- ==
SocketException==:读取网络失败
- 还有一些异常是程序逻辑编写不对造成的,应该修复程序本身。例如:
NullPointerException:对某个null的对象调用方法或字段
IndexOutOfBoundsException:数组索引越界
Exception又分为两大类
RuntimeException以及它的子类;
- 非
RuntimeException(包括IOException、ReflectiveOperationException等等)
- Tips : Java 规定:
- 必须捕获的异常,包括
Exception及其子类,但不包括RuntimeException及其子类,这种类型的异常称为Checked Exception。
- 不需要捕获的异常,包括
Error及其子类,RuntimeException及其子类。
- 不推荐捕获了异常但不进行任何处理
Try-catch-finally / Try-catch
try {
int index = scanner.nextInt();
System.out.println(arr[index]);
} catch (ArrayIndexOutOfBoundsException a){
System.out.println("Out of Bounds");
} finally {
scanner.close();
}