39-异常处理机制
抛出异常
捕获异常
异常处理五个关键字
try、catch、finally、throw、throws
package com.exception; public class Demo01 { public static void main(String[] args) { int a = 1; int b = 0; try { //try 监控区域 System.out.println(a/b); } catch (ArithmeticException e) { //catch() 捕获异常,参数为想要捕获的异常类型 System.out.println("b不能为0"); //捕获到后会执行这里 } finally { //finally 处理善后工作 } //可以不要 }
假设要捕获多个异常,增加catch(){}代码块,参数范围从小到大
package com.exception; public class Demo02 { public static void main(String[] args) { try { new Demo02().a(); } catch (StackOverflowError e) { System.out.println("捕获成功"); } catch (Error e){ System.out.println("捕获成功2"); } catch (Throwable e){ System.out.println("捕获成功3"); } finally { } } public void a(){ b(); } public void b(){ a(); } }
选中需要catch的代码,用ctrl+alt+T,直接生成try 、catch、finally
方法内可以用throw抛出异常
package com.exception; public class Demo03 { public static void main(String[] args) { new Demo03().test(1,0); } public void test(int a,int b){ if(b==0){ throw new ArithmeticException(); //主动抛出的异常,一般在方法内使用,无论下面是否计算,都会根据if条件主动抛出 } System.out.println(a/b); } }
方法上可以用throws抛出异常
package com.exception; public class Demo03 { public static void main(String[] args) { new Demo03().test(1,0); } public void test(int a,int b) throws ArithmeticException { System.out.println(a/b); } }
throw和throws的区别如下:
位置不同:throws作用在方法上,后面跟着的是异常的类;而throw作用在方法内,后面跟着的是异常的对象。
功能不同:throws用来声明方法在运行过程中可能出现的异常,以便调用者根据不同的异常类型预先定义不同的处理方式;throw用来抛出封装了异常信息的对象,程序在执行到throw时后续的代码将不再执行,而是跳转到调用者,并将异常信息抛给调用者。也就是说,throw后面的语句块将无法被执行(finally语句块除外)。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用