- What is the purpose of sys.exc_info()?
- 1 Answer 1
- Python sys.exc_info() method: get exception information
- Python sys.exc_info() Method
- Syntax
- Parameters
- Returns
- Example Codes
- Work With the sys.exc_info() Method
- Break Down the Tuple Returned by the sys.exc_info() Method
- Use Mathematical Equation With the sys.exc_info() Method
- Related Article — Python Sys
What is the purpose of sys.exc_info()?
Is there any case where type(exc) and exc.__traceback__ are different from the values returned by sys.exc_info() ? If not, when should I prefer one over the other? When I tested this (Python 3.7), the objects returned are referentially identical. Looking at the implementation of exc_info() in CPython, the first return value (the exception type) appears to be obtained by calling PyExceptionInstance_Class, which is exactly the same as type(exc) . However, I was unable to find how the traceback is set. (FWIW I am aware of the traceback.print_exc() shorthand, that is irrelevant to this question)
sys.exc_info() only works with the current exception, you can use the other operations on any exception.
@Barmar I understand that, I guess my question is more «Why does exc_info exist given that we can obtain the same values directly from the exception object?»
1 Answer 1
The __traceback__ attribute is available only since Python 3.0, so if you’re looking to make your code compatible with Python 2 you should use sys.exc_info() instead; otherwise, per PEP-3134, the introduction of the __traceback__ attribute is indeed meant to fully replace sys.exc_info() , and possibly deprecate it:
In today’s Python implementation, exceptions are composed of three parts: the type, the value, and the traceback. The sys module, exposes the current exception in three parallel variables, exc_type , exc_value , and exc_traceback , the sys.exc_info() function returns a tuple of these three parts, and the raise statement has a three-argument form accepting these three parts. Manipulating exceptions often requires passing these three things in parallel, which can be tedious and error-prone. Additionally, the except statement can only provide access to the value, not the traceback. Adding the __traceback__ attribute to exception values makes all the exception information accessible from a single place.
Python sys.exc_info() method: get exception information
sys.exc_info() is a function in the sys module that returns a tuple containing information about the current exception being handled. It’s useful when you need more control over how exceptions are caught and handled in your code. The tuple returned by sys.exc_info() contains three elements: (type, value, traceback).
- type : The type of the exception being handled.
- value : An instance of the exception class, containing more information about the error.
- traceback : A traceback object encapsulating the call stack at the point where the exception was raised.
Here’s a tutorial on using sys.exc_info() in Python:
def divide(a, b): return a / b try: result = divide(10, 0) except ZeroDivisionError: exc_type, exc_value, exc_traceback = sys.exc_info() print(f"An error occurred: : ")
In this example, we use sys.exc_info() to get information about the ZeroDivisionError exception. We then print the type and value of the exception.
import traceback def divide(a, b): return a / b try: result = divide(10, 0) except ZeroDivisionError: exc_type, exc_value, exc_traceback = sys.exc_info() print(f"An error occurred: : ") tb = traceback.format_tb(exc_traceback) for line in tb: print(line.strip())
In this example, we use the traceback module to format the traceback information obtained from sys.exc_info() and print it.
def divide(a, b): return a / b try: result = divide("10", 2) except (ZeroDivisionError, TypeError): exc_type, exc_value, exc_traceback = sys.exc_info() print(f"An error occurred: : ")
In this example, we use sys.exc_info() to get information about either a ZeroDivisionError or a TypeError exception.
In this tutorial, you learned how to use the sys.exc_info() function in Python to obtain detailed information about the current exception being handled. This allows you to gain more control over exception handling in your code and perform custom actions based on the type, value, and traceback of the exception.
Professional provider of PDF & Microsoft Word and Excel document editing and modifying solutions, available for ASP.NET AJAX, Silverlight, Windows Forms as well as WPF. We are dedicated to provide powerful & profession PDF/Word/Excel controls.
Python sys.exc_info() Method
- Syntax
- Parameters
- Returns
- Example Codes
Python sys.exc_info() method is an efficient way of getting information about the current exception that has occurred and is handled by the system. The data returned by this method is specific to both the current system thread and the current stack frame.
Syntax
Parameters
Returns
The method’s return type is a tuple consisting of three values. The values are as follows: ( type , value , traceback )
- type : denotes the type of exception being handled.
- value : it gets the instance of an exception type .
- traceback : it returns a traceback object that encapsulates the system call stack at the point where the exception originated.
Note that if the stack system handles no exception, a tuple containing three None values is returned.
Example Codes
Work With the sys.exc_info() Method
import sys import math try: x = 1/0 except: tuples = sys.exc_info() print(tuples)
(, ZeroDivisionError('division by zero'), )
Any number divided by 0 is not defined, so an exception is thrown. The method sys.exc_info() gives detailed information about the exception.
Break Down the Tuple Returned by the sys.exc_info() Method
import sys import math try: x = 1/0 except: tuples = sys.exc_info() print("Type: ", tuples[0]) print("Value: ", tuples[1]) print("Traceback: ", tuples[2])
Type: Value: division by zero Traceback:
The method sys.exc_info() gives us information about the exception in the form of a tuple . The tuple can also be accessed element-wise, as shown above.
Use Mathematical Equation With the sys.exc_info() Method
import sys import math a= 1 b= -8 c= 5 try: root1= (-(b)+(math.sqrt(b*b-4*a*c)))/(2*a) root2= (-(b)-(math.sqrt(b*b-4*a*c)))/(2*a) print ("Two real and distinct roots: ", root1, root2) except: e,p,t= sys.exc_info() print ("Two imaginary and distinct roots! Error generated: ",e,p) a= 2 b= 2 c= 1 try: root1= (-(b)+(math.sqrt(b*b-4*a*c)))/(2*a) root2= (-(b)-(math.sqrt(b*b-4*a*c)))/(2*a) print ("Two real and distinct roots: ", root1, root2) except: e,p,t= sys.exc_info() print ("Two imaginary and distinct roots! Error generated: ",e,p)
Two real and distinct roots: 7.3166247903554 0.6833752096446002 Two imaginary and distinct roots! Error generated: math domain error
In the above code, we implemented the quadratic formula. The answers are shown in floating point notations when we have two distinct real roots.
In the second attempt, the output was two different imaginary numbers that the system couldn’t process, so an exception was thrown.
Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.