【问题标题】:throw new Exception returns wrong line numberthrow new Exception 返回错误的行号
【发布时间】:2021-10-23 03:46:27
【问题描述】:

当我尝试通过抛出异常来获取堆栈跟踪时,我看到行号是“e.getMessage()”的确切行,而不是 throw 语句的行。仅当我在语句中有 e.getMessage() 时才会发生这种情况。这是正确的行为吗?

 public static void main(String[] args) {

    int x = 10;
    calculateX(x);

}

private static void calculateX(int x) {

    try {
        throw new ArithmeticException("" +
                "divide by 0");
    } catch (Exception e) {
        throw new RuntimeException("Run time error "

                + e.getMessage()
                , e);
    }
}

堆栈跟踪:

    Exception in thread "main" java.lang.RuntimeException: Run time error divide by 0
    at com.myTest.Main.calculateX(Main.java:49)
    at com.myTest.Main.main(Main.java:37)
Caused by: java.lang.ArithmeticException: divide by 0
    at com.myTest.Main.calculateX(Main.java:44)
    ... 1 more

第 49 行是 e.getMessage 行

【问题讨论】:

标签: java exception try-catch throw


【解决方案1】:

发生的事情是,

运行上面的代码你会得到这样的结果,

Exception in thread "main" java.lang.RuntimeException: Run time error divide by 0
    at com.maneesha.Main.calculateX(Main.java:17)
    at com.maneesha.Main.main(Main.java:10)
Caused by: java.lang.ArithmeticException: divide by 0
    at com.maneesha.Main.calculateX(Main.java:15)
    ... 1 more

如果我们首先查看这些行,它发生在方法调用calculateX()try 块中,它会抛出ArithmeticException,它会被catch 块捕获,然后抛出RuntimeException,发生的情况是我们捕获了我们期望的错误并将其作为新错误抛出,这就是为什么您可以在第 17 行看到错误。

因此,如果您阅读完整的堆栈跟踪,您将能够确定导致错误的原因。此外,最好不要捕获 Exception 并捕获特定错误,因为 catch(Exception e) 会捕获所有错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    相关资源
    最近更新 更多