Exception Notes and Traceback Metadata
Core idea
In Python 3.11 and later, error.add_note(text) appends a diagnostic string to an exception. The original type and message stay intact. Notes are available through __notes__ after a note has been added. An exception raised and caught also carries traceback metadata describing where it propagated.
try: int("bad")except ValueError as error: error.add_note("record 3") print(type(error).__name__) print(error.__notes__)The exception remains a ValueError; its notes list records the additional context.
Inspect formatted exception text
import tracebackerror = ValueError("invalid count")error.add_note("batch A")print("".join(traceback.format_exception_only(error)), end="")format_exception_only produces the exception message and notes, not the stack frames. The import uses a standard-library diagnostic module.
Check traceback availability
try: int("bad")except ValueError as error: print(error.__traceback__ is not None)A caught raised exception has traceback metadata. We inspect availability rather than printing environment-dependent paths.
Common mistake
Notes must be strings. Do not include passwords, personal data or raw private inputs in diagnostic notes or logs. Full tracebacks may reveal internal paths.
Practice
Add two synthetic notes to a ValueError, format only the exception text and check their order. Explain why this differs from a full traceback.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Add diagnostic context
Check your understanding of exception notes and tracebacks.
What is printed?
e = ValueError("bad")e.add_note("batch B")print(e.__notes__)What is printed?
e = ValueError("bad")e.add_note("batch B")print(str(e))What is printed?
try: int("x")except ValueError as e: print(e.__traceback__ is not None)What is suitable for a diagnostic note?