errors

package
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 6, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package errors ports cpython/Python/errors.c and the gating subset of cpython/Objects/exceptions.c. v0.3 ships the BaseException class hierarchy needed by v0.1 and v0.2, plus the Set/SetString/Format/ Occurred/Clear/Fetch/Restore/Raise/RaiseFrom/Print API.

ImportError and ModuleNotFoundError with the extra `name` and `path` named attributes that the import system stamps on every raise.

CPython: Objects/exceptions.c:L2932 ImportError_init

Index

Constants

This section is empty.

Variables

View Source
var (
	PyExc_BaseException       = newExcType("BaseException", []*objects.Type{objects.ObjectType()})
	PyExc_Exception           = newExcType("Exception", []*objects.Type{PyExc_BaseException})
	PyExc_LookupError         = newExcType("LookupError", []*objects.Type{PyExc_Exception})
	PyExc_ArithmeticError     = newExcType("ArithmeticError", []*objects.Type{PyExc_Exception})
	PyExc_RuntimeError        = newExcType("RuntimeError", []*objects.Type{PyExc_Exception})
	PyExc_KeyError            = newExcType("KeyError", []*objects.Type{PyExc_LookupError})
	PyExc_IndexError          = newExcType("IndexError", []*objects.Type{PyExc_LookupError})
	PyExc_OverflowError       = newExcType("OverflowError", []*objects.Type{PyExc_ArithmeticError})
	PyExc_ZeroDivisionError   = newExcType("ZeroDivisionError", []*objects.Type{PyExc_ArithmeticError})
	PyExc_NotImplementedError = newExcType("NotImplementedError", []*objects.Type{PyExc_RuntimeError})
	PyExc_AttributeError      = newExcType("AttributeError", []*objects.Type{PyExc_Exception})
	PyExc_NameError           = newExcType("NameError", []*objects.Type{PyExc_Exception})
	PyExc_TypeError           = newExcType("TypeError", []*objects.Type{PyExc_Exception})
	PyExc_ValueError          = newExcType("ValueError", []*objects.Type{PyExc_Exception})
	PyExc_StopIteration       = newExcType("StopIteration", []*objects.Type{PyExc_Exception})
	PyExc_SystemExit          = newExcType("SystemExit", []*objects.Type{PyExc_BaseException})
	PyExc_KeyboardInterrupt   = newExcType("KeyboardInterrupt", []*objects.Type{PyExc_BaseException})
	PyExc_ImportError         = newExcType("ImportError", []*objects.Type{PyExc_Exception})
	PyExc_ModuleNotFoundError = newExcType("ModuleNotFoundError", []*objects.Type{PyExc_ImportError})
)

Built-in exception type singletons. Names match CPython.

CPython: Objects/exceptions.c:L1937 PyExc_BaseException and friends

Functions

func AttachTraceback

func AttachTraceback(ts *state.Thread, entry traceback.Entry)

AttachTraceback prepends entry to the current exception's traceback. The VM (v0.6+) calls this on every frame unwind; v0.3 callers (Go-side) use it to record their own positions.

CPython: Python/traceback.c:L154 PyTraceBack_Here

func Clear

func Clear(ts *state.Thread)

Clear drops the current exception. Mirrors PyErr_Clear.

CPython: Python/errors.c:L488 _PyErr_Clear

func FormatException

func FormatException(exc *Exception) string

FormatException returns the multi-line rendering of exc, including any chained __cause__ / __context__ exceptions. Mirrors `traceback.format_exception`.

CPython: Python/traceback.c:L1129 _PyErr_Display

func HandleSystemExit added in v0.7.0

func HandleSystemExit(ts *state.Thread) (code int, handled bool)

HandleSystemExit inspects the current exception. If it is a SystemExit, the exit code is read off the args and the exception is cleared; the caller propagates the code. KeyboardInterrupt is surfaced as (-1, false) so the lifecycle layer can flip the runtime's unhandled_keyboard_interrupt flag (1639 wires that hook in once the signal table lands).

The bool return matches CPython's int return: true means the caller should exit with code; false means fall through to the normal print path.

CPython: Python/pythonrun.c:622 _Py_HandleSystemExitAndKeyboardInterrupt

func IsSubtype

func IsSubtype(sub, super *objects.Type) bool

IsSubtype reports whether sub inherits from super, walking the MRO.

CPython: Objects/typeobject.c:L2556 PyType_IsSubtype

func Match

func Match(exc *Exception, t *objects.Type) bool

Match reports whether exc's type inherits from t. Mirrors PyErr_GivenExceptionMatches.

CPython: Python/errors.c:L327 PyErr_GivenExceptionMatches

func NormalizeException

func NormalizeException(ts *state.Thread)

NormalizeException is a no-op in the modern API path; Set / Raise already produce a normalized Exception. Preserved for source-shape parity with CPython's legacy three-argument form.

CPython: Python/errors.c:L501 _PyErr_NormalizeException

func Print

func Print(ts *state.Thread, w io.Writer)

Print writes FormatException of the current exception to w and clears the slot. SystemExit is intercepted: if the exception is a SystemExit with an int (or None) code, the slot is cleared but nothing is written. Callers that need the exit code should use PrintEx instead.

CPython: Python/pythonrun.c:L656 PyErr_Print

func PrintEx added in v0.7.0

func PrintEx(ts *state.Thread, w io.Writer) int

PrintEx is the closer port of _PyErr_PrintEx: handle SystemExit first, then print the exception chain. Returns the exit code the caller should propagate.

CPython: Python/pythonrun.c:694 _PyErr_PrintEx

func Raise

func Raise(ts *state.Thread, exc *Exception)

Raise installs exc as the current exception. If a previous exception was current, it becomes exc.Context.

CPython: Python/errors.c:L83 _PyErr_SetObject (chaining branch)

func RaiseFrom

func RaiseFrom(ts *state.Thread, exc, cause *Exception)

RaiseFrom is `raise exc from cause`. It sets exc.Cause and suppresses context display.

CPython: Python/errors.c:L1438 _PyErr_SetFromCause

func Restore

func Restore(ts *state.Thread, typ *objects.Type, value *Exception, tb *traceback.Traceback)

Restore atomically installs an exception triple. Mirrors PyErr_Restore.

CPython: Python/errors.c:L37 _PyErr_Restore

func Set

func Set(ts *state.Thread, t *objects.Type, args *objects.Tuple)

Set raises an exception of type t with the given args.

CPython: Python/errors.c:L83 _PyErr_SetObject

func SetString

func SetString(ts *state.Thread, t *objects.Type, msg string)

SetString raises an exception of type t with a single-string args.

CPython: Python/errors.c:L283 _PyErr_SetString

func SuggestAttr

func SuggestAttr(name string, candidates []string) string

SuggestAttr returns a "Did you mean: 'name'?" candidate for an AttributeError, picking the closest match from candidates by Levenshtein distance. Returns "" when nothing is close enough.

CPython: Python/suggestions.c:L335 _Py_Offer_Suggestions for getattr

func SuggestKey

func SuggestKey(key string, candidates []string) string

SuggestKey returns a "Did you mean: 'key'?" candidate for a KeyError. CPython only suggests for string keys against string keys in a dict; gopy applies the same rule at the call site.

CPython: Python/suggestions.c:L398 _Py_Offer_Suggestions for KeyError

Types

type Exception

type Exception struct {
	objects.Header
	ExcType  *objects.Type
	Args     *objects.Tuple
	Cause    *Exception
	Context  *Exception
	Suppress bool
	Notes    *objects.List
	TB       *traceback.Traceback
}

Exception is the runtime representation of a raised Python exception. Mirrors PyBaseExceptionObject.

CPython: Objects/exceptions.c:L34 BaseExceptionObject

func Fetch

func Fetch(ts *state.Thread) (typ *objects.Type, value *Exception, tb *traceback.Traceback)

Fetch atomically removes and returns the current exception triple (type, value, traceback). Mirrors PyErr_Fetch.

CPython: Python/errors.c:L460 _PyErr_Fetch

func Format

func Format(ts *state.Thread, t *objects.Type, format string, args ...any) *Exception

Format raises an exception built from a printf-style template. Returns nil so callers can `return errors.Format(ts, ...)`.

CPython: Python/errors.c:L1138 _PyErr_FormatV

func New

func New(t *objects.Type, args *objects.Tuple) *Exception

New constructs an exception with the given type and args. Mirrors BaseException_new + BaseException_init.

CPython: Objects/exceptions.c:L42 BaseException_new

func Occurred

func Occurred(ts *state.Thread) *Exception

Occurred returns the current exception or nil. Mirrors PyErr_Occurred.

CPython: Python/errors.c:L138 _PyErr_Occurred

func (*Exception) IsException

func (e *Exception) IsException()

IsException implements the state.Exception marker.

func (*Exception) Message

func (e *Exception) Message() string

Message returns the exception's args[0] as a string when args has one item, matching CPython's BaseException.__str__ for single-arg exceptions.

CPython: Objects/exceptions.c:L226 BaseException_str

func (*Exception) TypeName

func (e *Exception) TypeName() string

TypeName returns the class name. Mirrors `type(exc).__name__`.

CPython: Objects/exceptions.c:L226 BaseException_str

type ImportError added in v0.8.0

type ImportError struct {
	Exception
	Name string // the module name that failed to import
	Path string // the file path associated with the error
}

ImportError wraps Exception and adds the `name` and `path` fields that the import machinery stamps on every ImportError instance.

CPython: Objects/exceptions.c:L2915 ImportErrorObject

func NewImportError added in v0.8.0

func NewImportError(msg, name, path string) *ImportError

NewImportError constructs an ImportError with the given message, module name, and path. Pass empty strings for name/path when unknown.

CPython: Objects/exceptions.c:L2932 ImportError_init

func NewModuleNotFoundError added in v0.8.0

func NewModuleNotFoundError(name string) *ImportError

NewModuleNotFoundError constructs a ModuleNotFoundError.

CPython: Objects/exceptions.c:L3065 PyExc_ModuleNotFoundError

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL