Java异常系列第二集——捕获所有异常

2017-12-25  本文已影响0人  will4it

本博客为个人原创,转载需在明显位置注明出处

这篇文章我们来聊聊捕获异常的内容,如果一个方法内部抛出两个或多个异常,外部捕获的顺序是怎样的?捕获到的异常,我们怎样打印出他的栈轨迹?如果捕获到异常之后不作任何处理再次抛出,他的栈轨迹会改变嘛?在项目里面我们经常会看到xxx Exception causedBy xxx Exception,这个是怎么回事?下面我们就来详细讨论一下(本篇代码较多)

异常匹配###

class CatchHelper {
    public void method(String arg1, String arg2) throws ParentException {
        if (arg1 == null) {
            throw new ChildException();
        }
         if (arg2 == null) {
            throw new ParentException();
         }
    }
}

@Test
public void testCatchException() {
    try {
        String arg1 = null;
        String arg2 = "";
         CatchHelper helper = new CatchHelper();
         helper.method(arg1, arg2);
    } catch (ChildException e) {
        System.out.println("Catch ChildException");
    } catch (ParentException e) {
        System.out.println("Catch ParentException");
    } catch (Exception e) {
        System.out.println("Catch Exception");
     }
}

代码中有两个自定义异常,从名称就可以明白,ChildException是继承自ParentException。再看代码,method方法中对两个参数判空,分别抛出这两个异常,按代码中的异常捕获,可以正常捕获两个异常。但是,如果将catch代码块中的ChildException和ParentException交换顺序,在ChildException编译器就会报错,提示该异常时unreachable的。因为异常捕获的顺序是从上往下的,如果上面的异常匹配了,下面的异常就没用了,代码中ChildException是ParentException的子类,若ParentException放在catch代码块的第一位,无论是Child还是Parent都会被捕获,排在第二位的ChildException就是无用的。总结成一句话就是:异常捕获要从上到下,从小到大

栈轨迹###

打印异常栈轨迹很简单,就是e.printStackTrace()方法的调用,打印出的是从异常抛出点的方法名到系统最底层的方法栈信息,不多解释,没有试过的可以自己去试下

重新抛出异常###

class RethrowHelper {

     public void methodA() throws MyException {
         System.out.println("this is methodA()");
         throw new MyException("thrown from methodA()");
     }

     public void methodB() throws MyException {
         try {
             methodA();
         } catch (MyException e) {
            System.out.println("Catch MyException in catch block from methodB()");      
            // e.printStackTrace();
            // 直接抛出捕获到的异常
            throw e;
         }
     }

     public void methodC() throws MyException {
         try {
             methodA();
         } catch (MyException e) {
             System.out.println("Catch MyException in catch block from methodC()");
             // e.printStackTrace();
             // 替换捕获到的异常的栈路径,然后再抛出
             e.fillInStackTrace();
             throw e;
         }
     }
}

@Test
public void testRethrow() {
    RethrowHelper helper = new RethrowHelper();
    try {
        helper.methodB();
     } catch (MyException e) {
         System.out.println("Main printStackTrace");
         e.printStackTrace();
     }
     
     try {
         helper.methodC();
     } catch (MyException e) {
         System.out.println("Main printStackTrace");
         e.printStackTrace();
     }
}

从代码中可以看出,methodB方法捕获到异常之后直接抛出,methodC方法捕获到methodA的异常之后,调用了e.fillInStackTrace()方法,然后再抛出。区别在于,如果直接抛出,异常的栈信息还是保持不变,也就是说testRethrow测试方法中打印出的methodB的异常信息仍然是从methodA抛出的。若像methodC一样,调用了e.fillInStackTrace()方法再抛出,异常就会先把当前方法作为栈顶信息,那么在外部testRethrow测试方法中捕获到的栈信息就是从methodC抛出的。光文字解释看起来可能有点费解,直接看运行结果:

Paste_Image.png

testRethrow测试方法捕获到的methodB的异常信息还是从methodA抛出的,异常信息没变

Paste_Image.png

methodC的异常信息就是从methodC抛出的,之前methodA的信息不存在了,看出区别了吧?

异常链###

class CauseHelper {
    public void setValue(String value) throws ValueValidException {
        if (value == null) {
            ValueInvalidException exception = new ValueInvalidException();
              // 将空指针异常设置为ValueInvalidException的起因,即CausedBy ......
              exception.initCause(new NullPointerException());
              throw exception;
         }
     }
}

@Test
public void testCause() {
     CauseHelper helper = new CauseHelper();
     try {
         helper.setValue(null);
     } catch (ValueValidException e) {
         e.printStackTrace();
     }
}

在开发过程中,我们经常会看到logcat上打印出的日志有两个异常信息,中间由causedBy连接,如上述代码的运行结果所示:

Paste_Image.png

setValue方法中判断value如果为空,就抛出一个自定义的ValueInvalidException,接着调用了异常对象的initCause方法,传入了一个NullPointerException作为参数,不难理解,这是给抛出的异常添加一个因果关系,说明我抛出的ValueInvalidException是由NullPointerException导致的,这样的异常信息更加专业全面。

关于捕获异常就聊到这里,下一篇要分享的是运行时多态中的异常,欢迎拍砖!

上一篇下一篇

猜你喜欢

热点阅读