throw和throws 的区别
一、throw 和 throws 的区别
throw 则是用来抛出一个具体的异常类型。
throws 用来声明一个方法可能产生的所有异常,可以跟多个异常类名,用逗号隔开 ,表示抛出异常,由该方法的调用者来处理。
throws表示出现异常的一种可能性,并不一定会发生这些异常。
小结
1.throw是语句抛出一个异常,throws是方法可能抛出异常的声明
2.throws出现在方法函数头,而throw出现在函数体
3.throw是指抛出一个异常的动作,而throws代表一种状态,指的是可能有异常抛出。
4.throw只能用于抛出一种异常,而throws可以抛出多个异常。
二、示例
示例来源:https://zhuanlan.zhihu.com/p/448314699
1、throw
TestThrow.java
public class TestThrow { /* * 定义一个检查非负数的函数 */ public static void checkNegativeNum(int num) { if (num < 0) { throw new ArithmeticException("不能输入负数!"); } else { System.out.println("输入的数字是:" + num + ",合法!"); } } public static void main(String[] args) { TestThrow obj = new TestThrow(); obj.checkNegativeNum(-3); } }
结果:
Exception in thread "main" java.lang.ArithmeticException: 不能输入负数! at TestThrow.checkNegativeNum(TestThrow.java:7) at TestThrow.main(TestThrow.java:15)
2、throws
TestThrows.java
public class TestThrows { public static int divideNum(int m, int n) throws ArithmeticException { int div = m / n; return div; } public static void main(String[] args) { TestThrows obj = new TestThrows(); try { System.out.println(obj.divideNum(45, 0)); } catch (ArithmeticException e) { System.out.println("Number cannot be divided by 0"); } System.out.println("Rest of the code.."); } }
结果:
Number cannot be divided by 0
Rest of the code..
3、throw和throws混合使用
TestThrowAndThrows.java
public class TestThrowAndThrows { static void method(String s) throws ArithmeticException, UnsupportedOperationException { System.out.println("Inside the method()"); if (s.equals("PUT")) { throw new UnsupportedOperationException("This request is not supported"); } else { throw new ArithmeticException("throwing ArithmeticException"); } } public static void main(String[] args) { try { method("GET"); } catch (ArithmeticException e) { System.out.println("caught ArithmeticException"); } catch (UnsupportedOperationException e) { System.out.println("caught UnsupportedOperationException"); } } }
结果:
Inside the method()
caught ArithmeticException
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix