“raise vs raise e” Explained!

In this article, we will be looking at the ‘raise’ vs ‘raise e’ statements. We will learn what they mean, their differences, and when they are used. 

The ‘raise’ statement is used to manually raise an exception in Python. For example, you can manually raise a ValueError exception like this

When to use raise by itself?

If you use the raise statement without specifying the type of exception you wish to raise your code will result in a RuntimeError as shown below.

If you look closely at the last line, it says

No active exception to reraise

This is because the Python interpreter expects you to use the raise statement by itself only on except blocks where there is an active Exception in the background

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

For example, you can write a user-friendly message before you let the error terminate the program:

    result = 65/0
except ZeroDivisionError:
    print("Error: You cannot divide a number by 0! Please try again.")
Error: You cannot divide a number by 0! Please try again.
Traceback (most recent call last):
  File "/home/main.py", line 2, in <module>
    result = 65/0
ZeroDivisionError: division by zero

Reason for the existence of this syntax

This way Python allows us to catch a triggered exception before it terminates the program, perform some additional actions such as cleaning up and logging the error, and then reraise it using the ‘raise’ statement to terminate the program.

This syntax is especially useful when the exception in question cannot be corrected in the except block and the only options are to

  • either raise the caught exception one level up to the calling code and let that deal with that given exception (for e.g. consider library code vs user code)
  • or we really need to terminate the program when this exception arises but we wish to log some stuff before the program termination.

If you wish to learn more I suggest reading the following article

Python Re-Raise the Same Exception

Usage of raise e

This is just another way of reraising an exception. The ‘raise e’ statement is very similar to the ‘raise’ statement. In fact, both of them are used to reraise an exception.

The only difference is when are these used. ‘raise e’ is used only when we have caught the exception and stored it in an object called ‘e’:

except SomeException as e:

In this case, using ‘raise e’ is the same as ‘raise SomeException’. This is obviously because the object ‘e’ contains the exception ‘SomeException’.

Here’s a quick example:                                                                                                                                               

    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'

Another point to be made here is that using the ‘raise e’ statement adds an extra piece of line to the output

The output is saying that the error was triggered by the ‘raise e’ statement in line 5.

Then it points out the original statement which triggered the error. That is in line 2.

Note: if you wish to learn everything about stack trace in one article, click here

Another advantage of using the ‘raise e’ instead of ‘raise’ is that we can access attributes of the caught exception via the object ‘e’ as shown in the example.

In this instance, we have used the filename attribute to customize our message to make it more user-friendly overall.

You can use these attributes for other scenarios as well such as logging and etc.

I hope everything makes sense at this point!

Now that we have learnt the various ways of raising exceptions, the next logical step is to have a look at the other side of the coin and learn how to debug exceptions raised by others like a professional. To continue your learning I invite you to checkout out our video on that topic!

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!

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
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