Exception Methods
BaseException.with_traceback() — exception method
Attach an existing traceback to this exception, returning the same exception instance. Passing None clears it. If the exception is later raised, the new raise site is added to its traceback. Exception chaining is often clearer for explaining why a different exception was raised.
Formal Syntax & Structure
python syntaxpython
error.with_traceback(tb, /)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| tb | traceback | None | Traceback chain to attach, or None to clear it. |
Return Value
BaseException
The same exception instance with an updated traceback.
Working Example
Example Snippetpython
try: 1 / 0except ZeroDivisionError as caught: tb = caught.__traceback__ error = RuntimeError("calculation failed") print(error.with_traceback(tb) is error) print(error.__traceback__ is tb) print(error.with_traceback(None).__traceback__ is None)