So I recently wrote a java class that extends exception and used an instance of this class to check cases and throw itself if an error occurs. I found out that when the caller of main catches this exception, 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 since this is not a common way of throwing exceptions. If it is intended behavior, what is the rational for this as it seems like the line number from where the exception was thrown would be more useful(and probably easier to track through the stack). Sample cases follow demonstrating expected behavior and unexpected.
Normal Exception throwing:
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 }
output:
Exception in thread "main" java.lang.Exception: Exception
at Test.main(Test.java:11)
My Approach(simplified):
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 }
output:
Exception in thread "main" java.lang.Exception: Exception
at Test.main(Test.java:5)
Yes. It is not only intended but documented. See the Javadoc for
java.lang.Throwable: ‘A throwable contains a snapshot of the execution stack of its thread at the time it was created.’ If you don’t want that, you have the option of callingfillInStackTrace()just before throwing it.