异常处理机制 拉勾IT课小编为大家分解
1、抛出异常
2、捕获异常
3、异常处理五个关键字:
try、catch、finally、throw、throws
注意:假设要捕获多个异常:需要按照层级关系(异常体系结构) 从小到大!
package exception;
/**
* Java 捕获和抛出异常:
* 异常处理机制
* 1、抛出异常
* 2、捕获异常
* 3、异常处理五个关键字
* try、catch、finally、throw、throws
* 注意:假设要捕获多个异常:需要按照层级关系(异常体系结构) 从小到大!
*/
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
/**
* try catch 是一个完整的机构体,finally 可以不要
* 假设IO流,或者跟资源相关的东西,最后需要关闭,关闭的操作就放在 finally 中
*/
try { //try 监控区域
System.out.println(a / b);
} catch (ArithmeticException exception){ //catch(想要捕获的异常类型) 捕获异常
System.out.println("程序出现异常,变量b不能为0");
} finally { //处理善后工作
System.out.println("finally");
}
System.out.println("-------------- 分隔符 --------------");
try {
new Test().a(); //无限循环
} catch (Error error){
System.out.println("Error");
} catch (Exception exception){
System.out.println("Exception");
} catch (Throwable throwable){
System.out.println("Throwable");
} finally {
System.out.println("finally");
}
}
public void a(){
b();
}
public void b() {
a();
}
}
捕获异常
联系我时,请说是在得易搜分类信息网看到的,谢谢!