所以我最近写了一个扩展异常的java类,并使用这个类的一个实例来检查情况并在发生错误时抛出它自己。我发现当 main 的调用者捕获到这个异常时,它说异常被抛出的那一行是异常被创建的那一行,而不是异常被抛出的那一行。我只是想知道这是为什么,以及它是否是 jvm 的预期行为,因为这不是抛出异常的常见方式。如果这是预期的行为,那么这样做的合理性是什么,因为抛出异常的行号似乎更有用(并且可能更容易通过堆栈进行跟踪)。示例案例展示了预期的行为和意外的行为。
正常异常抛出:
1 public class Test
2 {
3 public static void main(String ... args) throws Throwable
4 {
5 switch(5)
6 {
7 case 1: throw new Exception("Exception");
8 case 2: throw new Exception("Exception");
9 case 3: throw new Exception("Exception");
10 case 4: throw new Exception("Exception");
11 case 5: throw new Exception("Exception");
12 }
13 }
14 }
输出:
Exception in thread "main" java.lang.Exception: Exception
at Test.main(Test.java:11)
我的方法(简化):
1 public class Test
2 {
3 public static void main(String ... args) throws Throwable
4 {
5 Exception e = new Exception("Exception");
6 switch(5)
7 {
8 case 1: throw e;
9 case 2: throw e;
10 case 3: throw e;
11 case 4: throw e;
12 case 5: throw e;
13 }
14 }
15 }
输出:
Exception in thread "main" java.lang.Exception: Exception
at Test.main(Test.java:5)
最佳答案
the line it says the exception was thrown from is the line from where the exception was created, and not from where it was thrown. I'm just wondering why this is, and whether it is intended behavior for the jvm or not
是的。它不仅是有意的,而且被记录在案。请参阅 java.lang.Throwable
的 Javadoc:“throwable 包含其线程在创建时执行堆栈的快照。”如果您不想这样,您可以选择在抛出之前调用 fillInStackTrace()
。
关于java - jvm异常捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9954463/