异常
Exception
异常指程序中出现的不期而至的各种状况:文件找不到、网络连接失败等
分类
-
检查性异常:无法预见,如文件不存在
-
运行时异常:程序没有错误,运行出错
-
错误
异常体系机构
java.lang.Throwable作为所有异常的超类:
- 错误Error
- 异常Exception
Error和Exception区别:
- Error是致命错误,是程序无法控制和处理的,当出现错误时,Java 虚拟机(JVM)会选择终止进程
- Exception 是可以被程序处理的,并且再程序中应该尽可能地去处理这些异常
异常处理机制
int a = 1;
int b = 0;
// 假设要捕获多个异常,从小到大!
//ctrl + alt + T
try { //try监控区域
if (b == 0){
throw new ArithmticException(); //主动抛出异常
}
System.out.println(a/b);
}catch (Error e){ //捕获错误
System.out.println("error");
}catch (Exception e){ //捕获异常
System.out.println("exception");
}catch (Throwable t){ //捕获Throwable
System.out.println("throwable");
} finally { //处理后续工作
System.out.println("finally");
}
//finally 可以不用
public class Demo02 {
public static void main(String[] args) {
// new Demo02().test(1, 0);
try {
new Demo02().test(1, 0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void test(int a, int b) throws ArithmeticException{
// if (b == 0){
// throw new ArithmeticException(); //主动抛出异常,一般在方法中使用
// }
int c = a/b;
}
}
关键字:try、catch、finally、throw、throws
自定义异常
- 自定义异常类
- 在方法中通过throw关键字抛出异常对象
- 如果在当前抛出异常的处理方法中处理异常,可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws关键字指明要抛出的异常,继续进行下一步操作
- 在出现异常方法的调用者中捕获并处理异常
package exception;
//自定义异常类
public class MyException extends Exception{
//传递数字>10
private int detail;
public MyException(int a){
this.detail = a;
}
//toString: 异常的打印信息
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
package exception;
public class Demo03 {
//可能会存在异常的方法
static void test(int a) throws MyException{
System.out.println("传递的参数为:" + a);
if (a > 10){
throw new MyException(a);
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
}catch (MyException e){
System.out.println("MyException:" + e);
}
}
}
- 处理运行时异常时,采用逻辑去合理规避同时辅助 try-catch处理
- 在多重catch块后,可以加一个catch(Exception)来处理可能会被遗漏的异常
- 对于不确定的代码,也可以加上try-catch
- 尽量处理异常,加上代码处理块
- 添加finally语句释放占用资源,IO~