Wallers Jason
Wallers Jason

Reputation: 85

Line number in stacktrace in java

How does java know in which line of the compiled code the exception was thrown? Does each bytecode in class file has information about line of source file ?

Upvotes: 2

Views: 1934

Answers (2)

babybear
babybear

Reputation: 834

When a Java program throws an exception, the call stack is traced back until a matching catch clause is found. If no corresponding catch clause is found, the Java Interpreter catches the exception and prints the entire stack-trace. The traceback would include line-numbers only if they were compiled in.

Sun's javac includes line numbers by default whereas for some builds such as Ant's javac you need to make sure you've set debug level as true in the build.xml

Reference: Java Cookbook by Ian F Darwin, Getting Readable Tracebacks | Page 31

Upvotes: 3

teppic
teppic

Reputation: 7286

When you compile with the generate debug info flag (-g, or more specifically -g:{lines}) the compiler will add debug info to the class file.

For line numbers this is the LineNumberTable attribute.

Upvotes: 3

Related Questions