【问题标题】:Cannot find symbol in the chained exception [duplicate]在链接的异常中找不到符号 [重复]
【发布时间】:2015-01-12 08:59:39
【问题描述】:

在下面的程序中,当我们尝试获取 main exception 表示异常时,它会导致程序的第一个异常,然后它会给出类似这样的错误:cannot find symbol : e.getCause(); 但在删除此语句 System.out.println("Main Cause : " + e.getCause()); 后,我们成功获得了第一例外。

class chain_demo {
    static void demo() {
        //create an exception
        ArithmeticException e = new ArithmeticException("top Module");

        //cuase an exception
        e.initCause(new NullPointerException("Cause"));

        //throw exception
        throw e;
    }

    public static void main(String args[]) {
        try {
            demo();
        }
        catch(ArithmeticException e) {
            //display top_level exception
            System.out.println("Cautch : " + e);
        }

        //display cause exception
        //getting error here
        System.out.println("Main Cause : " + e.getCause());
    }
}

那么,我怎样才能得到原因异常。

【问题讨论】:

    标签: java exception-handling chained


    【解决方案1】:

    变量e 范围仅限于catch 块 移动

    System.out.println("Main Cause : " + e.getCause());
    

    在 catch 块内例如

       try {
            demo();
        }
        catch(ArithmeticException e) {
            //display top_level exception
            System.out.println("Cautch : " + e);
            System.out.println("Main Cause : " + e.getCause());
        }
    

    【讨论】:

    • 哦……错了……明白了……
    猜你喜欢
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 2016-03-17
    • 2011-12-22
    相关资源
    最近更新 更多