Fundamentals 16 min read

How Does Python’s VM Implement and Throw Exceptions?

The article dissects Python’s exception mechanism, showing how the interpreter and virtual machine raise, record, and propagate errors via thread‑state objects, traceback chains, and C‑level APIs, while also illustrating generator return values, Java checked exceptions, and the final printing of tracebacks.

Satori Komeiji's Programming Classroom
Satori Komeiji's Programming Classroom
Satori Komeiji's Programming Classroom
How Does Python’s VM Implement and Throw Exceptions?

Exceptions are not merely error signals; they can also transport data. The article starts with a generator example where the return value is wrapped in a StopIteration exception and retrieved via the exception’s value attribute.

It then notes that Java introduces checked exceptions, allowing a method to declare the exceptions it may raise so callers can handle them explicitly.

In Python, the interpreter consists of a compiler and a virtual machine, so exceptions may originate from either. Syntax errors are raised by the compiler, while runtime errors such as ZeroDivisionError or IndexError are raised by the VM. An example shows 1/0 triggering a ZeroDivisionError that can be caught with except ZeroDivisionError.

When a runtime error occurs, the VM stores the exception in the current PyThreadState object. It creates a traceback object that records the stack‑frame chain, linking each new traceback via the tb_next field, forming a linked list that mirrors the call stack.

The C API for exception handling is listed ( PyErr_SetNone, PyErr_SetObject, PyErr_SetString, PyErr_Occurred, PyErr_Clear, PyErr_Fetch, PyErr_Restore). The article walks through PyErr_Restore, showing how it retrieves the thread state, validates the arguments, swaps the old traceback, and sets the new raised exception.

Traceback creation is performed by PyTraceBack_Here, which calls _PyTraceBack_FromFrame. The latter allocates a PyTracebackObject (containing tb_next, tb_frame, tb_lasti, tb_lineno) and links it to the previous traceback, establishing the chain used later for printing.

During execution, the VM’s main loop ( _PyEval_EvalFrameDefault) contains an error label. When an exception is detected (e.g., division by zero returns NULL), control jumps to pop_2_error, then to error, where a new traceback is created for the current frame and linked. The VM then searches for a matching try/except block; if none is found, it unwinds the stack frame, repeats the traceback creation for the caller frame, and continues upward until the top‑level module is reached.

Finally, PyErr_Print traverses the linked traceback list, printing each frame’s information to stderr in the order: module, f, g, h. The printed stack trace allows developers to locate the exact source of the error. The article concludes that exceptions in Python are ordinary objects with an args tuple, and they can also be raised manually with the raise statement.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Exception HandlingRuntimeVirtual Machinestack-frameC API
Satori Komeiji's Programming Classroom
Written by

Satori Komeiji's Programming Classroom

Python and Rust developer; I write about any topics you're interested in. Follow me! (#^.^#)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.