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 ¶
- Variables
- func AttachTraceback(ts *state.Thread, entry traceback.Entry)
- func Clear(ts *state.Thread)
- func ErrnoSubclass(errno int) *objects.Type
- func FormatException(exc *Exception) string
- func HandleSystemExit(ts *state.Thread) (code int, handled bool)
- func IsSubtype(sub, super *objects.Type) bool
- func Match(exc *Exception, t *objects.Type) bool
- func NormalizeException(ts *state.Thread)
- func Print(ts *state.Thread, w io.Writer)
- func PrintEx(ts *state.Thread, w io.Writer) int
- func Raise(ts *state.Thread, exc *Exception)
- func RaiseFrom(ts *state.Thread, exc, cause *Exception)
- func Restore(ts *state.Thread, typ *objects.Type, value *Exception, tb *traceback.Traceback)
- func Set(ts *state.Thread, t *objects.Type, args *objects.Tuple)
- func SetHandled(ts *state.Thread, exc *Exception)
- func SetString(ts *state.Thread, t *objects.Type, msg string)
- func SuggestAttr(name string, candidates []string) string
- func SuggestKey(key string, candidates []string) string
- type Exception
- func Fetch(ts *state.Thread) (typ *objects.Type, value *Exception, tb *traceback.Traceback)
- func Format(ts *state.Thread, t *objects.Type, format string, args ...any) *Exception
- func Handled(ts *state.Thread) *Exception
- func New(t *objects.Type, args *objects.Tuple) *Exception
- func Occurred(ts *state.Thread) *Exception
- type ExceptionGroupInfo
- type ImportError
- type SyntaxErrorInfo
- type UnicodeErrorInfo
Constants ¶
This section is empty.
Variables ¶
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_FloatingPointError = newExcType("FloatingPointError", []*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_StopAsyncIteration = newExcType("StopAsyncIteration", []*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}) // Additional exceptions covered by CPython's hierarchy, ported so // stdlib code paths that reference them by name resolve at import. // // CPython: Objects/exceptions.c:L2200 the remainder of the family PyExc_AssertionError = newExcType("AssertionError", []*objects.Type{PyExc_Exception}) PyExc_MemoryError = newExcType("MemoryError", []*objects.Type{PyExc_Exception}) PyExc_EOFError = newExcType("EOFError", []*objects.Type{PyExc_Exception}) PyExc_BufferError = newExcType("BufferError", []*objects.Type{PyExc_Exception}) PyExc_RecursionError = newExcType("RecursionError", []*objects.Type{PyExc_RuntimeError}) PyExc_UnboundLocalError = newExcType("UnboundLocalError", []*objects.Type{PyExc_NameError}) PyExc_ReferenceError = newExcType("ReferenceError", []*objects.Type{PyExc_Exception}) PyExc_SystemError = newExcType("SystemError", []*objects.Type{PyExc_Exception}) PyExc_GeneratorExit = newExcType("GeneratorExit", []*objects.Type{PyExc_BaseException}) )
Built-in exception type singletons. Names match CPython.
CPython: Objects/exceptions.c:L1937 PyExc_BaseException and friends
var ( PyExc_BaseExceptionGroup = newExcType("BaseExceptionGroup", []*objects.Type{PyExc_BaseException}) PyExc_ExceptionGroup = newExcType("ExceptionGroup", []*objects.Type{PyExc_BaseExceptionGroup, PyExc_Exception}) )
BaseExceptionGroup wraps a sequence of leaf exceptions that all surfaced from a single try-block. PEP 654 splits it from ExceptionGroup so user code can match the BaseException-only form (KeyboardInterrupt, SystemExit) without losing the structural grouping. ExceptionGroup is the more common Exception-only form the BaseExceptionGroup constructor promotes to when every leaf is an Exception.
CPython: Objects/exceptions.c:873 BaseExceptionGroup CPython: Objects/exceptions.c:874 ExceptionGroup
var ( PyExc_OSError = newExcType("OSError", []*objects.Type{PyExc_Exception}) PyExc_BlockingIOError = newExcType("BlockingIOError", []*objects.Type{PyExc_OSError}) PyExc_ConnectionError = newExcType("ConnectionError", []*objects.Type{PyExc_OSError}) PyExc_ChildProcessError = newExcType("ChildProcessError", []*objects.Type{PyExc_OSError}) PyExc_BrokenPipeError = newExcType("BrokenPipeError", []*objects.Type{PyExc_ConnectionError}) PyExc_ConnectionAbortedError = newExcType("ConnectionAbortedError", []*objects.Type{PyExc_ConnectionError}) PyExc_ConnectionRefusedError = newExcType("ConnectionRefusedError", []*objects.Type{PyExc_ConnectionError}) PyExc_ConnectionResetError = newExcType("ConnectionResetError", []*objects.Type{PyExc_ConnectionError}) PyExc_FileExistsError = newExcType("FileExistsError", []*objects.Type{PyExc_OSError}) PyExc_FileNotFoundError = newExcType("FileNotFoundError", []*objects.Type{PyExc_OSError}) PyExc_IsADirectoryError = newExcType("IsADirectoryError", []*objects.Type{PyExc_OSError}) PyExc_NotADirectoryError = newExcType("NotADirectoryError", []*objects.Type{PyExc_OSError}) PyExc_InterruptedError = newExcType("InterruptedError", []*objects.Type{PyExc_OSError}) PyExc_PermissionError = newExcType("PermissionError", []*objects.Type{PyExc_OSError}) PyExc_ProcessLookupError = newExcType("ProcessLookupError", []*objects.Type{PyExc_OSError}) PyExc_TimeoutError = newExcType("TimeoutError", []*objects.Type{PyExc_OSError}) )
OSError is the base for every errno-driven exception. CPython dispatches OSError(errno, msg, ...) at construction time and promotes the result to the matching subclass via errnomap. We expose ErrnoSubclass for callers that build OSError instances on the Go side.
CPython: Objects/exceptions.c:1970 OSError_init
var ( PyExc_SyntaxError = newExcType("SyntaxError", []*objects.Type{PyExc_Exception}) PyExc_IndentationError = newExcType("IndentationError", []*objects.Type{PyExc_SyntaxError}) PyExc_TabError = newExcType("TabError", []*objects.Type{PyExc_IndentationError}) PyExc_IncompleteInputError = newExcType("_IncompleteInputError", []*objects.Type{PyExc_SyntaxError}) )
IndentationError fires for any block-structure mismatch (the parser raises it instead of SyntaxError when the offending token is INDENT or DEDENT). TabError is a stricter form that only fires when the mix is between tabs and spaces; CPython routes the -tt flag through it.
CPython: Objects/exceptions.c:2906 MiddlingExtendsException IndentationError CPython: Objects/exceptions.c:2913 MiddlingExtendsException TabError
var ( PyExc_UnicodeError = newExcType("UnicodeError", []*objects.Type{PyExc_ValueError}) PyExc_UnicodeEncodeError = newExcType("UnicodeEncodeError", []*objects.Type{PyExc_UnicodeError}) PyExc_UnicodeDecodeError = newExcType("UnicodeDecodeError", []*objects.Type{PyExc_UnicodeError}) PyExc_UnicodeTranslateError = newExcType("UnicodeTranslateError", []*objects.Type{PyExc_UnicodeError}) )
CPython: Objects/exceptions.c:3030 Py_UNICODE_ENCODE_ERROR_NAME panel
var ( PyExc_Warning = newExcType("Warning", []*objects.Type{PyExc_Exception}) PyExc_UserWarning = newExcType("UserWarning", []*objects.Type{PyExc_Warning}) PyExc_DeprecationWarning = newExcType("DeprecationWarning", []*objects.Type{PyExc_Warning}) PyExc_PendingDeprecationWarning = newExcType("PendingDeprecationWarning", []*objects.Type{PyExc_Warning}) PyExc_SyntaxWarning = newExcType("SyntaxWarning", []*objects.Type{PyExc_Warning}) PyExc_RuntimeWarning = newExcType("RuntimeWarning", []*objects.Type{PyExc_Warning}) PyExc_FutureWarning = newExcType("FutureWarning", []*objects.Type{PyExc_Warning}) PyExc_ImportWarning = newExcType("ImportWarning", []*objects.Type{PyExc_Warning}) PyExc_UnicodeWarning = newExcType("UnicodeWarning", []*objects.Type{PyExc_Warning}) PyExc_BytesWarning = newExcType("BytesWarning", []*objects.Type{PyExc_Warning}) PyExc_ResourceWarning = newExcType("ResourceWarning", []*objects.Type{PyExc_Warning}) PyExc_EncodingWarning = newExcType("EncodingWarning", []*objects.Type{PyExc_Warning}) )
Warning is the root of the runtime-warning class tree. All warnings raised by the warnings module bottom out here. Subclasses partition the categories the default filter list distinguishes (deprecation vs. user vs. resource and so on).
CPython: Objects/exceptions.c:2865 PyExc_Warning
Functions ¶
func AttachTraceback ¶
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 ¶
Clear drops the current exception. Mirrors PyErr_Clear.
CPython: Python/errors.c:L488 _PyErr_Clear
func ErrnoSubclass ¶ added in v0.10.1
ErrnoSubclass returns the OSError subclass that CPython would pick for the given errno. Unknown codes fall back to PyExc_OSError.
CPython: Objects/exceptions.c:2158 errnomap promotion in OSError_new
func FormatException ¶
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
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 ¶
IsSubtype reports whether sub inherits from super, walking the MRO.
CPython: Objects/typeobject.c:L2556 PyType_IsSubtype
func Match ¶
Match reports whether exc's type inherits from t. Mirrors PyErr_GivenExceptionMatches.
CPython: Python/errors.c:L327 PyErr_GivenExceptionMatches
func NormalizeException ¶
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 ¶
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
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 ¶
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 ¶
RaiseFrom is `raise exc from cause`. It sets exc.Cause and suppresses context display.
CPython: Python/errors.c:L1438 _PyErr_SetFromCause
func Restore ¶
Restore atomically installs an exception triple. Mirrors PyErr_Restore.
CPython: Python/errors.c:L37 _PyErr_Restore
func Set ¶
Set raises an exception of type t with the given args.
CPython: Python/errors.c:L83 _PyErr_SetObject
func SetHandled ¶ added in v0.12.3
SetHandled installs exc as the currently-handled exception. PUSH_EXC_INFO and POP_EXCEPT call this so sys.exc_info() can read it.
CPython: Python/errors.c _PyErr_SetHandledException
func SetString ¶
SetString raises an exception of type t with a single-string args.
CPython: Python/errors.c:L283 _PyErr_SetString
func SuggestAttr ¶
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 ¶
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 ¶
Fetch atomically removes and returns the current exception triple (type, value, traceback). Mirrors PyErr_Fetch.
CPython: Python/errors.c:L460 _PyErr_Fetch
func Format ¶
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 Handled ¶ added in v0.12.3
Handled returns the currently-handled exception (the one a running except handler is processing), or nil. Mirrors reading exc_info->exc_value off the thread state.
CPython: Python/errors.c _PyErr_GetHandledException
func New ¶
New constructs an exception with the given type and args. Mirrors BaseException_new + BaseException_init.
CPython: Objects/exceptions.c:L42 BaseException_new
func Occurred ¶
Occurred returns the current exception or nil. Mirrors PyErr_Occurred.
CPython: Python/errors.c:L138 _PyErr_Occurred
func (*Exception) ExceptionArgs ¶ added in v0.10.1
ExceptionArgs implements objects.ExceptionInstance: returns the args tuple, never nil.
CPython: Objects/exceptions.c:L184 BaseException_args_getter
func (*Exception) ExceptionType ¶ added in v0.10.1
ExceptionType implements objects.ExceptionInstance: returns the exception's class. Used by packages that can't import errors/ but need to read the exception's metadata, such as the vm's CLEANUP_THROW handler.
CPython: Objects/exceptions.c:L34 BaseExceptionObject (Py_TYPE access on tp_getset)
func (*Exception) IsException ¶
func (e *Exception) IsException()
IsException implements the state.Exception marker.
type ExceptionGroupInfo ¶ added in v0.10.1
ExceptionGroupInfo carries the structured payload: the message string and the tuple of nested exceptions. Subgroup/Split use this to project a subset out of a group while preserving ordering.
CPython: Objects/exceptions.c:886 BaseExceptionGroup_new
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
type SyntaxErrorInfo ¶ added in v0.10.1
type SyntaxErrorInfo struct {
Msg objects.Object
Filename objects.Object
Lineno int
Offset int
Text objects.Object
EndLineno int
EndOffset int
}
SyntaxError carries the structured payload the parser raises: filename, lineno, offset, text, end_lineno, end_offset, plus the optional msg. CPython exposes these as named attributes; the Go-side struct keeps them next to the underlying Exception so a caller can inspect them without reaching into args[1].
CPython: Objects/exceptions.c:2898 ComplexExtendsException SyntaxError
type UnicodeErrorInfo ¶ added in v0.10.1
type UnicodeErrorInfo struct {
Encoding objects.Object
Object objects.Object
Start int
End int
Reason objects.Object
}
UnicodeError is the parent for codec-side decode/encode failures. Each subclass carries the structured payload codecs.LookupError expects: encoding name, the offending object, the byte/codepoint range that triggered the failure, and the human reason.
CPython: Objects/exceptions.c:2973 UnicodeError