How Java Exceptions Work: A Quick Walkthrough
You write try / catch every day. But when a throw runs, what does the JVM actually do ? There is no magic: there is a table lookup, a stack unwinding procedure written down in the JVM specification, and - in one genuinely surprising case - a hardware trap and a kernel signal. Let's take it apart with real bytecode and real runs on JDK 21. What an exception is, per the spec The JVM spec ( JVMS…
A Java exception is an ordinary object that extends the Throwable class. It is thrown programmatically using the athrow instruction or triggered by JVM instructions detecting abnormal conditions. The exception contains a stack trace recording the execution stack frames at the time of construction.
When a thrown exception matches a catch block's type, the exception is caught and processed. If no matching catch block exists, the exception is propagated up the method invocation chain, causing subsequent methods to complete abruptly and discard their stack frames.
In the example provided, a simple try/catch block is demonstrated. The parse method attempts to parse a string, catching a NumberFormatException to return -1 instead. Running the class prints 42 and -1. The javap disassembly reveals the try block compiles to nothing; instead, there's handler code to store the exception and return -1. The exception table specifies that if a NumberFormatException is raised by any instruction within the try block, jump to the handler at offsets 5-7.
If an exception occurs and no matching catch block exists, the exception is propagated up the method invocation chain using the conceptual model described in the JVM specification. The HotSpot JVM may optimize this process by inlining calls and storing values in registers, but the observable behavior remains consistent with the specification.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.