019 异常
异常
程序运行流程之外的情况
异常分类
- 异常Exception
- 检查性异常
- 运行时异常:RuntimeException
一般由程序逻辑错误引起程序要从逻辑上尽量避免异常
- 错误ERROR
- 虚拟机生成抛出,大多与操作无关
- 虚拟机执行应用出错
异常处理
关键字:try catch finally throw throws
Ctrl+Alt+T:自动包裹
处理异常
public class TestException {
public static void main(String[] args) {
int a = 1;
int b = 0;
//捕获异常要从小到大
try { //try:监控区域
System.out.println(a / b);
} catch (Error e) { //catch(想要捕获的异常):捕获异常 throwable:最高异常
System.out.println("ArithmeticException异常,除数不能为0");
} catch (Exception e) {
System.out.println("Exception");
e.printStackTrace(); //打印错误的栈信息
//System.exit(0); //手动结束程序
} catch (Throwable t) {
System.out.println("Throwable");
} finally { //最终都会执行
//一般关闭流等资源
System.out.println("finally");
}
}
}
抛出异常
//假设这个方法中,处理不了这个异常,方法上抛出异常
public void test(int a, int b) throws ArithmeticException{
if (b == 0) {
//主动抛出异常抛出至上一级,上级没有处理会程序停止
throw new ArithmeticException();//一般用在方法中
}
System.out.println(a / b);
}
自定义异常
合理规避并辅助try-catch处理
在多重catch中最后可加exception处理被疏漏的异常
对于不确定的代码可以加try-catch消除潜在异常
尽量处理异常
尽量finally释放占用的资源
public class MyException extends Exception {
//自定义的异常:传递数字>10
private int detial;
public MyException(int detial) {
this.detial = detial;
}
//toString:异常的打印信息
@Override
public String toString() {
return "MyException{" + detial + '}';
}
}
如有错误,可评论指出,谢谢。


浙公网安备 33010602011771号