except block are for handling exceptions, the
raise keyword on the contrary is to raise an exception.
Following is the syntax:
Taking a simple usage example:
Traceback (most recent call last): File "main.py", line 1, in <module> raise ZeroDivisionError ZeroDivisionError: division by zero
If you have a piece of code where along with exception handling you have put in place some conditional statements to validate input etc, then in case of the conditions failing we can either just print a message or simple raise an exception which can then get handled by the common exception handling mechanism.
See the code below,
a = 10 b = 9 try: print(a/b) except ZeroDivisionError: print("Please enter valid integer value")
Consider the above code where we have handled
ZeroDivisionError, in this code we want to add a new validation for restricting user from inputting negative values.
Then we can simply add a new condition and use the
raise keyword to raise an exception which is already handled.
a = 10 b = 9 try: # condition for checking for negative values if a < 0 or b < 0: # raising exception using raise keyword raise ZeroDivisionError print(a/b) except ZeroDivisionError: print("Please enter valid integer value")
By this example we want to explain to you why and where we should use
raise keyword to explicitly raise an exception.
raiseWithout Specifying Exception Class
When we use the
raise keyword, it's not necessary to provide an exception class along with it. When we don't provide any exception class name with the
raise keyword, it reraises the exception that last occured.
This is used generally inside an
except code block to reraise an exception which is catched.
a = 10 b = 0 try: print(a/b) except ZeroDivisionError: raise
Traceback (most recent call last):
File "main.py", line 4, in
raiseWith an Argument
We can also provide an argument while raising an exception which is displayed along with the exception class name on the console.
We can pass any string for describing the reason for the exception or anything else.
raise ValueError("Incorrect Value")
Traceback (most recent call last): File "main.py", line 1, in <module> raise ValueError("Incorrect Value") ValueError: Incorrect Value