1 什么是异常
异常分类:
2 异常体系结构
Error:
Exception:
3 Java异常处理机制
抛出异常
捕获一次
异常处理五个关键字:try、catch、finally、throw、throws
package com.exception;
public class test01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { //try监控区域
System.out.println(a/b);
}catch (ArithmeticException e){ //catch捕获异常,里面放要捕获的异常类型,最高为throwable
System.out.println("程序出现异常,变量b不能为0");
}finally { //处理善后,一定会执行 可以不用 ( 一般涌来关闭资源等
System.out.println("finally");
}
}
}
在捕获多个异常时,需要从小到大。
快捷键:command + option +t 选中语句,按快捷键,可以使用常用语句
package com.exception;
public class test02 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//快捷键:command + option +t
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace(); //打印错误的栈信息
} finally {
}
}
}
主动抛出异常: