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.