异常处理机制
- 异常的抛出与捕获
public class Test {
public static void main(String[] args) {
int a=1;
int b=0;
//假设要捕获多个异常:从小到大
try {//try监控区域
// if (b==0){//主动的抛出异常 throw throws
// throw new ArithmeticException();//主动的抛出异常
// }
new Test().a();
System.out.println(a/b);
}catch (Error e){//catch(想要捕获的异常类型) 捕获异常
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable t){//范围最大的放最下面
System.out.println("Throwable");
}finally {// 处理善后工作(可以不要)
System.out.println("finally");
}
}
public void a(){
b();
}
public void b(){
a();
}
}
范围最大的要放在最下面,否则会报错(因为范围包含会发生重复捕获)
public class Test {
public static void main(String[] args) {
try {
new Test().test(1, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
//假设这方法中,处理不了这个异常,方法上抛出异常
public void test(int a,int b){
if (b==0){//主动的抛出异常 throw throws
throw new ArithmeticException();//主动的抛出异常,一般在方法中使用
}
System.out.println(a/b);
}
}
无try catch时,程序遇到异常会直接停止,而加上后,程序会捕获异常,会继续执行完
- 异常等级
自定义异常
- 用户自定义异常,只需继承Exception类即可
- 步骤
- 创建自定义异常类
- 在方法中通过throw关键字抛出异常对象
- 如果在当前抛出异常的方法中处理异常,可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws关键字指明要抛出给方法调用者的异常,继续进行下一步操作
- 在出现异常方法的调用者中捕获并处理异常
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 +
'}';
}
}
测试类
public class Test {
//可能会存在异常的方法
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(1);
} catch (Exception e) {
System.out.println("MyException=>"+e);
}
}
}
-
注意
- 处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
- 在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
- 对于不确定的代码,也可以加上try-catch,处理潜在的异常
- 尽量去处理异常,切忌只是简单的调用printStackTrace()去打印输出
- 具体如何处理异常,要根据不同的业务需求和异常类型去决定
- 尽量添加finally语句块去释放占用的资源