How to Print an Exception in Python

Vaibhav Vaibhav Feb 02, 2024
  1. Print an Exception Using try-except-finally Blocks in Python
  2. Print Exception Using the traceback Module in Python
How to Print an Exception in Python

In Python, an Exception is an error. There are many errors or Exceptions in Python, such as TypeError, SyntaxError, KeyError, AttributeError, etc. We use try-except-finally in Python to handle these Exceptions because, without these blocks, these exceptions would halt the program’s execution. try-except-finally blocks in Python can be used to print these exceptions without stopping the program’s execution.

Consider the following code snippet.

dictionary = {
    "hello": "world",
number = 25

    number = number + dictionary["hello"]
except Exception as e:


TypeError("unsupported operand type(s) for +: 'int' and 'str'",)

In the above code, we first initialize a dictionary with hello as a key pointing to the string value world, and a variable number. Then inside the try block, we are trying to access the string value stored in the dictionary and adding it to the number variable.

This statement is both practically and conceptually wrong because it is impossible to add a string to an integer. So the except block catches this error and prints the Exception object associated with this exception in the console.

Python has a built-in module, traceback, for printing and formatting exceptions. And it makes it easy to print the whole exception in the console.

In Python, you can manually raise exceptions using the raise keyword. In the following code snippet, we’ll use the raise keyword to raise exceptions inside the try block.

import traceback

    raise KeyError
except Exception as e:


Traceback (most recent call last):
  File ".\", line 4, in <module>
    raise KeyError

In the code above, we raise a KeyError exception and use the print_exc() function from the module traceback to print the exception. This function prints the information about the exception and is a shorthand for traceback.print_exception(*sys.exc_info(), limit, file, chain).

To learn more about print_exception() function refer to the official docs here

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article - Python Exception