Skip to main content

Get Exception Info

Description

The get_exception_info function retrieves the filename and line number where the most recent exception occurred, if available.

Function Signature:

def get_exception_info() -> tuple[str, int] | tuple[None, None]:

Parameters

  • None

Returns

  • tuple[str, int]: A tuple containing the filename and line number of the exception if an exception was raised.
  • tuple[None, None]: If no exception information is available, it returns a tuple of None values.

Example Usage

try:
# Example code that raises an exception
1 / 0
except ZeroDivisionError:
filename, line_number = get_exception_info()
print(f"Exception occurred at {filename}, line {line_number}")

Notes

  • This function uses sys.exc_info() to retrieve information about the most recent exception.
  • If an exception traceback is available, it extracts the filename and line number from the traceback object.
  • If no exception is available (or no traceback is present), it returns None for both values.

Error Handling

  • This function is designed to handle cases where no exception traceback is available by returning None, None.