异常
定义
异常体系结构
Error
Exeption
捕获和抛出异常
测试类
package test.demo;
public class Demo1 {
public static void main(String[] args) {
int a=1;
int b=0;
//假设要捕获多个异常:从小到大
try {//try 监控区域
System.out.println(a/b);
}catch (Error c){//catch(想要捕获的异常类型) 捕获异常
System.out.println("NO");
}catch (Exception c){
System.out.println("dd");
}catch (Throwable c){
System.out.println("DD");
} finally {
System.out.println("finally");
}//finally 是必须执行的模块
//finally 可以不要,IO,资源,关闭!
}
public void a(){
b();
}
public void b(){
a();
}
}
//快捷键CTRL+alt+t快速生成catch
原本
现在
关键字
try:尝试处理某些代码
catch:捕获
finally:无论try中的执不执行finally句都会执行 finally不能单独使用。
throw,throws:用于抛出异常(也可从方法抛出)
常见异常
1.数组越界异常:ArrayIndexOutOfBoundsException
2.数字格式化异常:NumberFormatException
3.算数异常:ArithmeticException
4.空指针异常:NullPointerException
测试类2
package test.demo;
public class Demo1 {
public static void main(String[] args) {
int a=1;
int b=0;
try {
new Demo1().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void test(int a,int b) throws ArithmeticException{
if(b==0){//throw throws
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
System.out.println(a/b);
}
}
throws &throw 基本格式
使用格式:在方法声明时使用
修饰符 返回值类型 方法名(参数列表) throws AAAExcepiton,BBBExcepiton...{
throw new AAAExcepiton("产生原因");
throw new BBBExcepiton("产生原因");
...
}
自定义异常
子类
package test.demo;
//自定义的异常类
public class MyException extends Exception{
private int detail;
public MyException( int d) {
this.detail = d;
}
//异常打印信息toString
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
父类
package test.demo;
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(11);
} catch (MyException e) {
System.out.println(e);
}
}
}
工作经验总结
- 处理运行异常时,采用逻辑去合理规避同时辅助try-catch处理
- 在多重catch块后面,可以加上一个catch(Exception)来处理可能会被遗漏的异常
- 对于不确定的代码,也可以加上try-catch,处理潜在的异常
- 尽量去处理异常,切忌只是简单地调用printStackTrace()去打印输出
- 具体如何处理异常,要根据不同的业务需求和异常类型去确定
,采用逻辑去合理规避同时辅助try-catch处理 - 在多重catch块后面,可以加上一个catch(Exception)来处理可能会被遗漏的异常
- 对于不确定的代码,也可以加上try-catch,处理潜在的异常
- 尽量去处理异常,切忌只是简单地调用printStackTrace()去打印输出
- 具体如何处理异常,要根据不同的业务需求和异常类型去确定
- 尽量添加finally语句块去释放占用的资源
依照B站up主遇见狂神说
根据自己理解编写