【发布时间】: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 行
【问题讨论】:
-
这……很有趣。该行为由
String-连接中的换行符触发。 With linebreak (Ideone demo) --- Without linebreak (Ideone demo) -
如果使用 JDK16 运行,行号不会改变
标签: java exception try-catch throw