美文网首页
Java异常淹没、返回值栈

Java异常淹没、返回值栈

作者: 远o_O | 来源:发表于2017-06-14 19:21 被阅读85次

    返回值栈,异常淹没

    • 当Java程序的方法中有异常处理块的时候,执行引擎可能需要处理多了返回值,这时候,执行引擎会将处理到的返回值,压入到返回值栈中。
    • 不建议在finally中进行return,因为当有异常发生且catch块中又抛出新的异常,会淹没异常,这是非常糟糕的。
    /**
     * Created by 编程只服JAVA on 2017.06.14.
     */
    public class ExceptionTest {
        public static void main(String[] args) {
            System.out.println(testExc());
        }
    
        static int testExc(){
            int a = 0;
            try {
                a = a/0;
                return 1;
            }catch (ArithmeticException e){
                throw new IOException("就想抛出来");
            }finally {
                return 2;
            }
        }
    }
    

    运行结果:

    image.png

    运行结果分析:

    • 异常果然被淹没
    • 返回值栈中,先压入1,又压入2,因此最后返回值为2

    异常栈追踪,异常处理策略

    • 当一个方法中有异常发生后,JVM会先查看本方法中是否有该异常处理程序(即catch块),如果没有,则会将异常沿着方法调用栈,不断向上抛,并且逐个寻找是否有处理该异常的程序,如果没有,则会最终抛到main方法,程序停止运行。
    /**
     * Created by 编程只服JAVA on 2017.06.14.
     */
    public class ExceptionTest {
        public static void main(String[] args) throws IOException {
            method1();
        }
    
        static void method1() throws IOException {
            method2();
        }
    
        static void method2() throws IOException {
            method3();
        }
    
        static void method3() throws IOException {
            throw new IOException("method3's Exception");
        }
    }
    

    运行结果,注意观察堆栈跟踪:


    image.png

    相关文章

      网友评论

          本文标题:Java异常淹没、返回值栈

          本文链接:https://www.haomeiwen.com/subject/hwreqxtx.html