问题描述
快捷键 Ctrl + Alt + t (+win)生成异常分析(如果按了没反应那就是有热键冲突了把qq关掉就得了)
关键字 try 、catch 、 finally 、 throw 、 throws;
-
try:监控区域,检测有没有出现异常
-
catch:捕获异常
-
finally:处理善后工作(无论结果如何都会执行finally里面的内容)
-
throw:在方法中抛出异常
-
throws:在方法上抛出异常 异常捕获Throwable >Exception >Error
自定义异常
-
处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
-
在多重catch块后面,可以加一个catch (Exception) 来处理可能会被遗漏的异常
-
对于不确定的代码,也可以加上try-catch,处理潜在的异常
-
尽量去处理异常,切忌只是简单地调用printStackTrace()去打印输出
-
具体如何处理异常,要根据不同的业务需求和异常类型去决定
-
尽量添加finally语句块去释放占用的资源
-
package com.exception;
public class Test {
public static void main(String[] args) {
new Test().test(1,0);
//用try与catch的好处是程序不会停止,可以检测出异常后处理掉;
}
//假设方法中处理不了这个异常,
public void test(int a, int b) throws ArithmeticException{//主动抛出异常
if(b==0) { //throw throws
throw new ArrayStoreException();//主动抛出异常 一般在方法使用
}
}
}
/*
//假设要捕获多个异常,捕获异常的类型得从小到大!
try{//监控区域,检测有没有出现异常
System.out.println(a/b);
}catch(Error e){//捕获异常 catch(想要捕获的类型)
System.out.println("Error");
}catch(Exception t){
System.out.println("Exception");
}catch(Throwable h){
System.out.println("Throwable");
} finally{//处理善后工作(无论结果如何都会输出finally里面的内容)
System.out.println("finally");
}
//可以不要finally ,io流、资源,finally在这段代码中的作用是关闭
//Ctrl + Alt + t 快捷键 System.out.println(a/b);/
*/
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)