How JVM knows line numbers during runtime?

Viewed 334

When a .java file is compiled, it produces a .class file containing bytecode. JVM takes that bytecode and executes it. Byte during this step, if an exception is thrown, there is also a mention of in which line did this error occurred in source code. But the line numbers in bytecode and source code will be completely different and bytecode also does not store line numbers during compilation since I did not find any mnemonics related to it (and also storing line numbers would simply increase the code size). So can someone tell me how JVM gets the exact line number in the source code where the exception was thrown.

1 Answers

The JVM specification provides a reference for the format of class files (bytecode). The line numbers are stored in an attribute LineNumberTable. You can also try running the following Java disassembler command (javap provided by the JDK) on a certain .class file to see them:

javap -l MyClass.class
Related