Python Re-Raise the Same Exception

In this article, we will learn how to reraise an exception after you have caught it. We will be explaining the 2 methods to do it with examples. Without further ado, let’s begin!

Exceptions can be re-raised for various reasons such as;

  • Logging the exception details before the program is terminated
  • Cleaning resources to deallocate memory space
  • Adding additional information to make it user-friendly

Here are 2 ways to do that:

Method#1: raise inside the except block

The first method is simply to use the raise statement inside the except block:

try:
  #some code that might raise an error
except SomeException: 
  #do some additional action here
  raise

In this code, the try block contains code that might trigger an error. If there are no errors, the except block won’t be executed.

If there is an error, the execution reaches the except block. You can do what you need to do here and then use the raise statement to re-raise the exception. Here

The raise statement tells the interpreter to throw the exception last caught

embeddedinventor.com

Here’s how you could use implement this in your code:

import logging

try:
    result = 65/0
except ZeroDivisionError:
    error = "division by zero"
    logging.error(error)
    raise
ERROR:root:division by zero
Traceback (most recent call last):
  File "/home/main.py", line 4, in <module>
    result = 65/0
ZeroDivisionError: division by zero

You can log stuff to a file instead of a console to keep a permanent record if you wish. Next, let us see another interesting method for achieving a similar result!

Method#2: raise e inside except ErrorType as e

This is an alternative to the first method with a slight change. Here we save the exception in a variable. Then we raise the exception using the variable.

In the following syntax, the exception is stored in the variable ‘e’:

try:
  #some code that might raise an error
except SomeException as e: 
  #do some additional action here
  raise  e

If this syntax is something you are seeing for the first time, I invite you to watch the following video we made on that topic.

If you wish to learn the same through an article, here is the link

Python: “except Exception as e” Meaning Explained!

Coming back to the topic, here are some examples of how to implement method#2 in code.

import logging

try:
    result = 65/0
except ZeroDivisionError as e:
    logging.error(e)
    raise  e
ERROR:root:division by zero
Traceback (most recent call last):
  File "/home/main.py", line 7, in <module>
    raise e
  File "/home/main.py", line 4, in <module>
    result = 65/0
ZeroDivisionError: division by zero

In this method, the output contains an extra line.

  • It says the exception was raised in line 7, which is the line we manually raised.
  • Then it says line 4 which is where the original error occurred (result = 65/0)

If you wish to learn everything about what is inside the error message and how to make use of it like a professional I suggest reading the following article we wrote on that topic.

Python: Details contained in an Exception

Also, notice that in this method printing the message becomes easier plus we are able to access certain attributes of the exception object ‘e’. Let me show you what I mean with another example.

try:
    my_file = open("example.txt", "r")
except FileNotFoundError as e:
    print(f"Uh-oh! Your file '{e.filename}' was not found, please try again.")
    raise e
Uh-oh! Your file 'example.txt' was not found, please try again.
Traceback (most recent call last):
  File "/home/main.py", line 5, in <module>
    raise e
  File "/home/main.py", line 2, in <module>
    my_file = open("example.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'example.txt'

In this example, we can tailor our message by accessing the filename attribute of the exception object and then printing it accordingly to the user making it friendlier overall.

And with that, I will end this article.

I hope you found reading this article useful!

Feel free to share it with your friends and colleagues!

There are a ton of other exception-related articles on our website. If you wish to handle exceptions like a pro check these articles and videos!

Related Articles

Exceptions in Python: Explained for Beginners!

Python: “raise exception from e” Meaning Explained!

Related Videos:

Python: Debug Exceptions like a Pro!

Exceptions in Python: Explained for Beginners!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn