zoukankan      html  css  js  c++  java
  • 异常:调用链顺序

    在异常调用链当中:异常对象创建顺序(栈内进行),和异常堆栈链显示顺序恰好相反(出栈顺序)

    源码:

    package lsh.element;
    
    public class ExceptionChains {
        public static void main(String[] args) {
            try {
                method1();
            } catch (Exception2 e) {
                e.printStackTrace();
            }
        }
    
        public static void method1() throws Exception2 {// 靠近栈顶,所以消息先出栈;后实例化
            try {
                method2();
            } catch (Exception2 e) {
                throw new Exception2("New info from method1", e);
            }
        }
    
        public static void method2() throws Exception2 {// 靠近栈底,所以消息后出栈;先实例化
            throw new Exception2("New info from method2");
        }
    
    }
    
    class Exception2 extends Exception {
        private static final long serialVersionUID = 1L;
        static {
            System.out.println("Exception2 - static");
        }
        {
            System.out.println("Exception2 - instance");
        }
    
        Exception2(String msg) {
            super(msg);
            System.out.println("Exception2 - init");
        }
    
        public Exception2(String message, Throwable cause) {
            super(message, cause);
            System.out.println("Exception2 - init2");
        }
    }

    执行结果:

    Exceptin2 - static
    Exception2 - instance
    Exception2 - init
    Exception2 - instance
    Exception2 - init2
    lsh.element.Exception2: New info from method1
        at lsh.element.ExceptionChains.method1(ExceptionChains.java:16)
        at lsh.element.ExceptionChains.main(ExceptionChains.java:6)
    Caused by: lsh.element.Exception2: New info from method2
        at lsh.element.ExceptionChains.method2(ExceptionChains.java:21)
        at lsh.element.ExceptionChains.method1(ExceptionChains.java:14)
        ... 1 more

    以上:上半部分是栈内正常执行顺序;下半部分的异常信息顺序。

  • 相关阅读:
    匿名函数与内置函数(python3入门)
    迭代器和生成器(python3入门)
    python中文件操作方法(python3入门)
    python所有数据类型及操作(python3入门)
    Python语法命令学习-Day3(作业练习)
    Python语法命令学习-Day3(零基础)
    构建之法阅读笔记01
    学习进度条
    软件工程个人作业01
    阅读计划
  • 原文地址:https://www.cnblogs.com/InformationGod/p/9716224.html
Copyright © 2011-2022 走看看