How to Print Exception Stack Traces in Python?5 Jan 2025 | 4 min read The suspicious code will be retained in the try block and handled by the except block in order to produce the stack trace for an exception. In order to handle the exception that was created, we shall output the stack trace here. Understanding the issue and the source of the code mistake is aided by the publishing stack trace for an exception. Not only that, but the stack trace also indicates the error's location. The general format of an error stack trace is as follows:
Example: Method 1: By Using the print_exc() MethodThis function stacks trace entries from the traceback object (tb) and prints exception information to a file. Syntax: Parameters: The following arguments are accepted by this method:
Return: None. Code: Program Explanation: Using exception handling, the Python program illustrates how to handle an index error that arises while attempting to access an element at index (5) that is beyond the boundaries of the array 'A.' The program tries to access 'A[5],' and if an exception arises, it sends a traceback inside the try block. The stack trace, which contains details about the exception, is printed using the print_exc() function. It outputs the IndexError and the associated stack trace in this instance. The code that follows the try-except block is performed even when an exception is handled inside the try block because the program still runs in spite of the exception, and the message "end of program" is printed. Output:
Traceback (most recent call last):
File "C:/Python27/hdg.py", line 8, in
value=A[5]
IndexError: list index out of range
end of program
Method 2: By Using the print_exception() MethodThis function stacks trace entries from the traceback object (tb) and prints exception information to a file. Syntax: Parameters: The following parameters are accepted by his method:
Return: None. Code: Program Explanation: This Python program illustrates how to handle exceptions in the case of a division by zero. The program tries to execute the operation a / b inside the try block, where 'a' is initialized to 4 and 'b' to 0. An exception is raised as dividing by zero is prohibited. The exception and Traceback are caught by the except block. The stack trace is printed using the print_exception(*sys.exc_info()) function, which also provides the exception's type, value, and Traceback. The code after the try-except block is performed even if an exception is handled within the try block since the program still runs and the message "end of program" is written in spite of the exception. Output:
Traceback (most recent call last):
File "C:/Python27/hdg.py", line 10, in
value=a/b
ZeroDivisionError: integer division or modulo by zero
end of program
|
How to get a String Left Padded with Zeros in Python
? String padding is a concept used in programming primarily in languages like Python to change the length of a string by adding additional characters This option is often used to ensure sorting or sorting of data types, e.g as information displayed in the same user...
7 min read
numpy.argmin() in Python
The NumPy returns the array's min element's indices in each axis.argmin() function. Syntax : numpy.argmin(array, axis = None, out = None) Parameters : array : Input array to work on axis : [int, optional] Along a specified axis like 0 or 1 out : [array optional] Provides a feature to insert...
3 min read
Python For Data Analysis
Python is one of the programming languages widely used by Data Scientists and Analysts. With various built-in mathematical libraries and functions, Python makes it easier to calculate mathematical problems and to perform data analysis. Data analysis is the process of gathering, transforming and handling data to...
8 min read
Bipartite Graph in Python
In this tutorial, we will learn about bipartite graphs and the ways to check if a given graph is bipartite or not. A bipartite graph is one whose vertices can be separated into two independent sets. Let the two sets be S1 and S2. The two...
14 min read
Check if a File or Directory Exists using Python
A document is a compilation of data or details kept on a computer under a particular title. It could be a record, a picture, a film, software, or any other type of information. Documents may come with additions that display their extensions, such as .txt,...
5 min read
Python Program to Sort Numbers Based on 1 Count in their Binary Representation
To sort numbers in Python agreeing to the number of 1s in their double representation, to begin with change over each number to its binary form. Another, count the number of 1s within the binary representation. At last, sort the numbers concurring to this number....
4 min read
Lucas Primality Test using Python
Introduction: In number theory and cryptography, prime numbers are crucial. Numerous techniques have been created for the goal of identifying prime numbers, which is essential in many applications. The Lucas primality test is one such algorithm, and it provides a quick way to tell whether a...
3 min read
3 Easy Ways to Crosstab in Pandas
Python is a high-level, interpreted, and dynamically typed language acknowledged for its simplicity and readability. It uses indentation to outline code blocks, enhancing clarity. Python supports more than one programming paradigm, including procedural, item-orientated, and functional programming. Its full-size well-known library and active network make...
4 min read
How to Use Pickle to Save and Load Variables in Python
? Introduction As one of the most versatile and powerful programming languages, Python offers a lot of tools and libraries for various activities. Indeed, one of the commonly used modules to preserve data over time is known as pickle. 'Pickle' enables the conversion of Python objects to...
7 min read
PySide6 Module in Python
In this article, you will be discovering what PySide6 is, its major functions and how you can integrate this tool into your application to create great, robust, cross-platform GUI apps with relative ease. Will also be discovering what PySide6 is, with basic example and understanding main...
11 min read
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India