Python › Exception Handling

How do you access details about the exception currently being handled, like its type, value, and traceback, using sys.exc_info()?

Intermediate

Answer

sys.exc_info() returns a 3-tuple (exception type, exception instance, traceback object) for the exception CURRENTLY being handled — mostly superseded by simply using 'except Exception as e' to directly capture the instance, but still useful for lower-level introspection or re-raising logic.
import sys

try:
    1 / 0
except ZeroDivisionError:
    exc_type, exc_value, exc_tb = sys.exc_info()
    print(exc_type)   # <class 'ZeroDivisionError'>
    print(exc_value)  # division by zero
Real-world example Building generic exception-logging or reporting middleware that needs low-level access to full exception details.

Common follow-ups: Why is 'except Exception as e' generally preferred over manually calling sys.exc_info() in modern code?