Python Reference ยท Exceptions
BaseException and Exception
Reference for Python BaseException and Exception: args, with_traceback, add_note, custom exceptions, when to catch Exception and why not BaseException.
BaseException is the root of all exceptions. Exception is its subclass and the base of every ordinary error: all built-in errors and nearly all user-defined ones inherit from it. The classes that bypass Exception (SystemExit, KeyboardInterrupt, GeneratorExit) signal "the program should stop", not "something failed".
You raise instances, catch classes, and subclass Exception to make your own error types.
class AppError(Exception): pass try: raise AppError("something went wrong", 42) except Exception as error: print(error.args) # ('something went wrong', 42)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
BaseException(*args) Exception(*args)
| Name | Description |
|---|---|
*args |
Any positional arguments. They are stored in the args tuple; str(error) shows the single argument, or the tuple for several. |
Useful members:
| Member | Description |
|---|---|
args |
Tuple of the constructor arguments. |
with_traceback(tb) |
Sets __traceback__ and returns the exception. |
add_note(note) |
Adds a string to __notes__ (3.11+); notes print after the message in tracebacks. |
__cause__, __context__ |
The exception linked by raise ... from and the one being handled when this was raised. |
__traceback__ |
The traceback object, or None. |
Raises: add_note() raises TypeError if the note is not a string.
Usage notes
- Catch
Exception, notBaseException, in a catch-all handler, and re-raise or log what you cannot handle. SwallowingKeyboardInterruptmakes programs impossible to stop. - Subclass
Exceptionfor your own errors. A short docstring orpassbody is enough; add attributes when callers need data. - Custom
__init__: callsuper().__init__(message)soargsandstr()work. Pickling an exception re-creates it fromargs, so extra required constructor parameters can break it. - Raising a class (
raise ValueError) instantiates it with no arguments. - Names bind only inside the handler.
except Exception as error:deleteserrorwhen the block ends; copy it first if you need it later. BaseExceptiondirect use is rare: only for control-flow signals you do not wantexcept Exceptionto see.- Messages should say what failed and with what value; avoid ending them with punctuation habits that look odd in tracebacks.