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).
- import sys
- try:
- c = a / b
- except:
- print("There's a problem")
- print(sys.exc_info())
- print(sys.exc_info()[0])
- print(sys.exc_info()[1])
- 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.