02 捕获和抛出异常
捕获和抛出异常(异常处理机制)
- 捕获:catch 一般 try,catch,finally 一起使用
- 抛出:throw,throws的区别!
五个关键字:try , catch , finally, throw, throws
注意点:
// 异常处理机制: 抛出和捕获
// try catch finally throw throws
// finally 可以不要,一般用来处理善后工作 比如 IO流,资源 ,关闭!: scanner.close()
// ctrl + alt + t :快捷键,选择代码块,进行快捷键组合操作,自动生成
package com.zhan.base06Exception.demo02;
public class Test02 {
// 异常处理机制: 抛出和捕获
// try catch finally throw throws
//对比各个程序及运行结果
public static void main(String[] args) {
int a=10;
int b=0;
System.out.println(a/b); // 出现异常
}
}
package com.zhan.base06Exception.demo02;
public class Test02_01 {
public static void main(String[] args) {
int a=10;
int b=0;
try{ // try 监控区域 尝试执行里面的代码块(捕获到异常的话则不执行,才叫 try)
System.out.println(a/b);
}catch (Error e){
System.out.println("error");
}catch (Exception e){
System.out.println("exception! 分母不能为零");
} catch (Throwable e){
// catch() 捕获异常 ; Throwable e 对应 最大的异常类类和对象
// 捕获到异常的话执行里面的代码块
// 捕获多个异常:从上往下,异常范围逐渐扩大(可以平级或者扩大,但不能缩小)
System.out.println("程序出现异常 ,分母不能为零");
}finally{ //处理善后工作 , 无论有没有错误或者异常都执行里面的代码块
System.out.println("finally, 表示程序结束");
}
// finally 可以不要,一般用来处理善后工作 比如 IO流,资源 ,关闭!: scanner.close()
}
}
package com.zhan.base06Exception.demo02;
public class Test02_02 {
public static void main(String[] args) {
int a=10;
int b=0;
// ctrl + alt + t :快捷键,选择代码块,进行快捷键组合操作,自动生成
try {
System.out.println(a/b);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
System.out.println("finally");
}
}
}
package com.zhan.base06Exception.demo02;
public class Test02_03 {
public static void main(String[] args) {
int a=10;
int b=0;
try {
new Test02_03().test(10,0);
} catch (ArithmeticException e) {
throw new RuntimeException(e);
} finally {
System.out.println("程序仍可以继承运行下去");
}
}
// 假设这个方法中处理不了这个异常,在这个方法上将这个异常往外抛出去 throws(方法头)
public void test(int a,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException(); // throw (方法体里面) 主动抛出异常,一般在方法中使用
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?