异常
异常
运行中出现的不期而至的状况
参数,网络,文件,操作错误等引起的
- 检查性异常
- 运行时异常
- 错误ERROR
- 关键字:try catch throw throws finally
抛出异常: throw主动抛出异常 throws用于方法上抛出异常
捕获异常:catch
try {//监视区域
System.out.println(a/b);
}catch (ArithmeticException e){//捕获异常:出现异常后执行 括号内的为捕获的异常类型
System.out.println("出现异常");
}finally { //无论是否出现异常都会执行
System.out.println("finally");
}
自定义异常
-
创建异常类
-
继承Exception类
package Exception;
public class demo02 extends Exception {
//传递数字>10抛出异常
private int detail;
public demo02(int a){
this.detail = a;
}
//toString:异常的打印信息
@Override
public String toString() {
return "demo02{" +
"detail=" + detail +
'}';
}
}