X-异常,自定义异常,异常链
来源:互联网 发布:gsm是什么卡的网络 编辑:程序博客网 时间:2024/06/04 01:12
throw—将产生的异常抛出(动作),写在方法体中
throws— 声明将要抛出何种类型的异常(声明),告诉调用者所要抛出的异常
public void 方法名(参数列表)
throws 异常列表(多个异常用逗号隔开){
//调用会抛出异常的方法或者:
throw new Exception();
}
package throwtest;public class DrunkException extends Exception{public DrunkException(){}public DrunkException(String message){super(message);}}
package throwtest;public class ChainTest {public static void main(String[] args) {ChainTest ch=new ChainTest();try {ch.testChain1();} catch (Exception e) {e.printStackTrace();}}private void testChain1() throws Exception{try{testChain2();}catch(DrunkException e){//1RuntimeException newExc=new RuntimeException("抛出由DrunkException引起的运行异常");//1newExc.initCause(e);//2RuntimeException newExc=new RuntimeException(e);throw newExc;}}private void testChain2() throws DrunkException{throw new DrunkException("抛出DrunkException");}}
1和2分别通过initCause()和构造器设置cause
控制台信息:
java.lang.RuntimeException: 抛出由DrunkException引起的运行异常at throwtest.ChainTest.testChain1(ChainTest.java:17)at throwtest.ChainTest.main(ChainTest.java:8)Caused by: throwtest.DrunkException: 抛出DrunkExceptionat throwtest.ChainTest.testChain2(ChainTest.java:24)at throwtest.ChainTest.testChain1(ChainTest.java:15)... 1 more
异常链:JDK1.4以后所有Throwable的子类子构造器中都可以接受一个cause对象作为参数,
这个cause就异常原由,代表着原始异常,即使在当前在当前位置创建并抛出行的异常,也可以
通过这个cause追踪到异常信息最初发生的位置.只有Error,RuntimeException提供了带cause
参数的构造器,其他的异常只有通过initCaouse()来设置cause.
阅读全文
0 0
- X-异常,自定义异常,异常链
- 异常处理+异常+处理异常+自定义异常
- 异常与自定义异常
- 【异常】自定义异常
- 异常----自定义异常
- 自定义异常链处理
- 自定义异常
- 自定义异常
- 自定义异常
- 自定义异常
- 自定义异常
- 自定义异常
- 自定义异常
- 自定义异常
- 自定义异常
- 自定义异常
- 自定义异常
- 自定义异常
- xynuoj 磁带最大利用率问题 酒馆浪人的博客
- python ValueError: cannot switch from automatic field numbering to manual field specification
- 音频和视频概述
- c语言,数据类型转换
- 微信小程序3——小程序与服务端通信
- X-异常,自定义异常,异常链
- 上阶梯问题
- 智能支付终端功能清单
- react-native实现轮播图
- html标签(一)
- 分布式锁
- 删除链表中重复的结点
- 六大设计原则之单一职责
- 【游戏知识】当你打“王者农药”卡到坑时,你可以这样装X