day09-Exception
异常 Error和Exception
检查性异常
运行时异常
错误ERROR
-> 异常处理机制
异常也是也是对象,所有异常的超类:java.lang.Throwable:
- Error
- Exception
-
- IOException
- RuntimeException
异常处理的五大关键字:
try,catch,finally,throw,throws
package com.example.demo.exception;
public class Demo01 {
public static void main(String[] args) {
int a=0;
int b=20;
//ctrl+alt+t 对选中的代码快速生成try或if或者循环或者其他
try{//try 尝试运行
System.out.println(b/a);
new Demo01().a();
if (a==0){
throw new ArithmeticException();
}
}catch(Exception e){//捕获异常 参数为想要捕获的类型 最高为Throwable,java.lang.Throwable
System.out.println("Exception"+e);//catch可以像if-else那样写,但是先尝试捕获小的异常再到大的
}catch (Error e){
System.out.println("Error "+e);
} finally{//最终会运行的
System.out.println("finally");
}
//finally常用于IO,资源,关闭等等
}
public void a(){b();}
public void b(){a();}
}
package com.example.demo.exception;
public class Demo02 {
public static void main(String[] args) {
try {
new Demo02().test(1,0);
} catch (Exception e) {
throw new RuntimeException("E:"+e);
} finally {
}
}
public void test (int a,int b) throws ArithmeticException{//throws用于方法上,方法中解决不了的异常
if (b==0){
throw new ArithmeticException();//主动抛出异常,一般用于方法
}
System.out.println("ok");
}
}
暂时结束一部分
🌸慢慢了解又不了解,知道了一些又感觉自己不会的更多了,但是不管怎么说,学习到的东西总是在自己脑袋里,在一次次练习实践中成长的。🔥
Peace & Love😘