Sys.exc_info() Function in Python

In Python, the exc_info() function allows you to obtain information about errors and exceptions that occur during the execution of a script. The exc_info() function is part of the sys module.

Syntax

import sys
sys.exc_info()

What is it used for?

The exc_info() function returns information about the most recent exception that was raised.

It is particularly useful for handling unexpected errors within a try except block.

Note: Since this is a function from an external library (sys), to use it in a Python script, you need to import the module using the import or from import statement.

    A Practical Example

    In this script, I use a try except block to perform a division (line 3).

    1. import sys
    2. try:
    3. c = a / b
    4. except:
    5. print("There's a problem")
    6. print(sys.exc_info())
    7. print(sys.exc_info()[0])
    8. print(sys.exc_info()[1])
    9. print(sys.exc_info()[2])

    However, several errors might occur during the execution of line 3.

    For instance, division by zero, non-numeric values, undefined variables, etc.

    With a generic except clause, I can catch any type of error.

    Then, I use the sys.exc_info() function to determine the specifics of the exception.

    The output of the script is as follows:

    There's a problem
    (<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero',), <traceback object at 0x02DDB8C8>)
    <class 'ZeroDivisionError'>
    division by zero
    <traceback object at 0x02DDB8C8>

    The exc_info() function provides three very useful pieces of information:

    • The type of error (most recent exception)
    • The exception value
    • The traceback object

    What is the traceback? It is an object that allows you to view the program's call stack at the moment the exception occurred.

    By processing this information, you can handle any exception within the script and avoid an unexpected program crash.

    And so on.

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Python (exceptions)

    1. How to handle exceptions

    Statements

    1. try except
    2. pass
    3. raise
    4. sys.exc_info()