异常捕捉机制和捕捉到的异常
- 异常捕捉机制格式:
try{
//程序代码块
}catch(Type1 id1){
//处理Type1异常的代码
}catch(Type2 id2){
//处理Type2异常的代码
}catch(Type3 id3){
//处理Type3异常的代码
}
try后面可以跟多个catch处理不同异常的解决方案
public static void f(){
int[] arr = new int[10];
arr[10] = 10;
}
public static void main(String[] args) {
try {
f();
} catch (Exception e) {
System.out.println("b");
}
System.out.println("main");
}
在这段代码中,我们在try中调用了函数,他会通过函数中抛出的异常去执行相匹配的catch
- 异常捕捉机制:

捕捉到的异常
public static void f(){
int[] arr = new int[10];
arr[10] = 10;
}
public static void main(String[] args) {
try {
f();
} catch (Exception e) {
System.out.println("b");
System.out.println(e.getMessage());
System.out.println(e);
e.printStackTrace();
}
System.out.println("main");
}
如果我们捕捉到了异常e,我们可以将e这个值直接输出,通过e.getMessage()来获取哪个值报的异常,也可以通过e.printStackTrace()来获取异常的全部信息

try {
f();
} catch (Exception e) {
System.out.println("b");
System.out.println(e.getMessage());
System.out.println(e);
e.printStackTrace();
throw e;
}
我们也可以通过throw e将异常再次抛出
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现