When one layer of your program catches an error from another and raises its own, the information about the original cause must not be lost. Python solves it with exception chaining.
class ConfigError(Exception):
pass
def read_port(text):
try:
return int(text)
except ValueError as e:
raise ConfigError(f"invalid port: {text!r}") from e # chains the cause
try:
read_port("80a")
except ConfigError as e:
print(e) # invalid port: '80a'
print(type(e.__cause__).__name__) # ValueError
print(e.__cause__) # invalid literal for int() with base 10: '80a'
# Without "from", Python keeps the previous error in __context__
try:
try:
1 / 0
except ZeroDivisionError:
raise KeyError("x")
except KeyError as e:
print(type(e.__context__).__name__, e.__cause__) # ZeroDivisionError None
# "from None" hides the original error
try:
try:
int("x")
except ValueError:
raise RuntimeError("failure") from None
except RuntimeError as e:
print(e.__cause__, e.__suppress_context__) # None True
# add_note (Python 3.11+): add context without changing the error type
err = ValueError("bad data")
err.add_note("line 4")
err.add_note("file a.txt")
print(err.__notes__) # ['line 4', 'file a.txt']
raise NewError(...) from emarkseas the cause (__cause__) and the traceback shows both errors, one after the other.- If you raise an exception inside an
exceptwithoutfrom, Python keeps the previous one in__context__anyway. from Nonesuppresses the chaining: use it only when the original cause is noise that confuses the user.add_note()(Python 3.11+) adds text to the error without changing its type; it is shown in the traceback. It is handy for adding the line or file being processed.
You practice it in Chained errors.