Menu

How Java Exceptions Work: A Quick Walkthrough
📰

How Java Exceptions Work: A Quick Walkthrough

DEV Community: tutorial·Vishnu B·3 days ago
#UORQEBnk
#devtotutorial#devto#dev#exception#catch
Reading 0:00
15s threshold

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 2.11.9 ) says: "An exception is thrown programmatically using the athrow instruction. Exceptions can also be thrown by various Java Virtual Machine instructions if they detect an abnormal condition."

So two sources: your explicit throw (compiled to one bytecode instruction, athrow ), and the JVM itself (a bad cast, an array index out of range, a null dereference). Either way, the exception is an ordinary object - allocated on the heap like any other - whose class extends Throwable . What makes it special is what the constructor records. From the Throwable JavaDoc : "Fills in the execution stack trace.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.