java基础学习:异常机制02(Exception)
-
异常处理机制:
-
抛出异常
-
-
-
异常处理的5个关键词:
-
try ,catch , finally ,throw ,throws
-
-
代码案例1:
public class Test {
public static void main(String[] args) {
int a =1;
int b=0;
//假设要捕获多个异常:从小到大去捕获
try {//try监控区域
System.out.println(a/b);
} catch (Error r) {//catch 捕获异常
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable t){
System.out.println("Throwable");
}finally {//处理善后工作
System.out.println("finally");
}
//finally 可以不要finally,假设IO,资源,关闭!
//try..catch快捷键:ctrl+alt+T
}
} -
代码案例2:
public class Test2 {
public static void main(String[] args) {
int a =1;
int b=0;
try {
new Test2().cat(1,0);//匿名内部类
} catch (Exception e) {
e.printStackTrace();
}
//try..catch快捷键:ctrl+alt+T
}
//假设这个方法中,处理不了这个异常,方法上抛出异常
public void cat(int a ,int b) throws Exception{
if(b==0){ //throw throws
throw new ArithmeticException();//主动抛出异常 //主动抛出异常一般都写在方法中
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律