异常概念
异常是以类和对象的形式存在的,异常发生时底层时new对象
Object下有Throwable
(可抛出的)
Throwable
下有两个分支:Error
(不可处理,直接退出JVM)和Exception
(可处理的)
Exception下有两个分支:
Exception
的直接子类:编译时异常。(要求程序员在编写程序阶段必须预先对这些异常进行处理,如果不处理编译器报错,因此得名编译时异常)RuntimeException
:运行时异常。(在编写程序阶段程序员可以预先处理,也可以不管)
常见异常
java.lang.NullPointerException
: 空指针异常
java.lang.ClassCastException
: 类型转换异常(运行时异常)
原因:Animal a = new Bird();
Cat c = (Cat)a;
ArrayIndexOutOfBoundsException
: 数组下标越界异常
原因:int[] array = new int[3];
array[4];
NumberFormatExcepet
: 数字格式化异常
StackOverflowError
:栈内存溢出错误
原因:一直压栈,没有弹栈,栈内存不够用。
解决:1.先检查递归的结束条件是否正确,不正确的话进行修改直至正确
2.假设递归的条件没问题,我们可以手动调整JVM的栈内存初始化大小
3.调整了大小之后还出现这个错误,只能继续扩大栈内存大小
java -X 查看调整堆栈大小的参数
java.lang.ArithmeticException :/by zero
算术异常(运行时异常)
原因:int i = 5/0;
java.io.FileNotFoundException
: 找不到文件异常
原因:系统找不到指定的文件
异常对象的两个方法
获取异常简单描述信息:
String msg = e.getMessage;
打印异常追踪的堆栈信息:
e.printStackTrace;
finally
- 通常在finlly中完成资源的释放/关闭
- finally子句中的代码是最后执行的,并且一定会执行
- finally子句必须和try一起出现,不能单独编写
throws 和 throw 的区别
- throws 在方法声明位置上使用,表示上报异常信息给调用者
- throw 手动抛出异常
异常例子
例子1
public class ExceptionTest {
public static void main(String[] args) {
System.out.println("main begin!");
try {
m1();
} catch (FileNotFoundException e) {
System.out.println("文件不存在!");
// 打印异常堆栈信息
e.printStackTrace(); //FileNotFoundException 系统找不到指定的文件
}
System.out.println("main over!");
}
private static void m1() throws FileNotFoundException {
System.out.println("m1 begin!");
m2();
System.out.println("m1 over!"); //不执行
}
private static void m2() throws FileNotFoundException {
System.out.println("m2 begin!");
m3();
System.out.println("m2 over!"); //不执行
}
private static void m3() throws FileNotFoundException {
new FileInputStream("D:\\JavaSE");
System.out.println("以上代码出异常,本代码不执行"); //不执行
}
}
运行结果:
main begin!
m1 begin!
m2 begin!
文件不存在!
main over!
例子2
try {
System.out.println("try...");
return;
} finally {
System.out.println("finally...");
}
运行结果:
try...
finally...
例子3
try {
System.out.println("try...");
// 退出JVM
System.exit(0); // 只有退出JVM,finally子句不会执行
} finally {
System.out.println("finally...");
}
运行结果:
try...
例子4
public static void main(String[] args) {
System.out.println(m());
}
public static int m(){
int i = 100;
try {
return i;
} finally {
i++;
}
}
运行结果:
100