Skip to main content

Get Line Number

Description

The get_line_number function retrieves the line number where the most recent exception occurred, if available.

Function Signature:

def get_line_number() -> int | None:

Parameters

  • None

Returns

  • int: The line number where the most recent exception occurred.
  • None: If no exception traceback is available, it returns None.

Example Usage

try:
# Example code that raises an exception
1 / 0
except ZeroDivisionError:
line_number = get_line_number()
print(f"Exception occurred at 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 line number from the traceback object.
  • If no exception is available (or no traceback is present), it returns None.

Error Handling

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