Topics

Exception Handling: raise

Welcome to a tutorial on Raise keyword on Python Exception Handling. The raise keyword is to raise an exception, this is quite opposite to try and accept.

Check out the syntax below:

raise EXCEPTION_CLASS_NAME

Check out the example below:

raise ZeroDivisionError

Output:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    raise ZeroDivisionError
ZeroDivisionError: division by zero

 

From the example above, if you have a piece of code that is along with exception handling, you have put in place some conditional statements to validate input, and so on. Also, in case of the conditions fail we can either print a message or simply raise an exception which can then get handled by the common exception handling mechanism. 

Check out the example:

a = 10
b = 9
try:
    print(a/b)
except ZeroDivisionError:
    print("Please enter valid integer value")

From the above code, we have handled ZeroDivisionError. In the program, we want to add a new validation for restricting a user from inputting negative values.

Now, we can just add a new condition and use the raise keyword to raise an exception that 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.

 

raise Without Specifying Exception Class

If the raise keyword is used, it's not necessary to provide an exception class along with it. Also, if an exception class name is not provided with the raise keyword, it re-raises the exception that occurred last.

In addition, this is used generally inside an except code block in other to re-raise an exception that is cached.

Check out the example below:

a = 10
b = 0
try:
    print(a/b)
except ZeroDivisionError:
    raise

Output:

Traceback (most recent call last):
  File "main.py", line 4, in 
    print(a/b)
ZeroDivisionError: division by zero

 

raise With an Argument

in this case, we can as well provide an argument while raising an exception that is displayed along with the exception class name on the console.

Check out the example, as we can pass any string for describing the reason for the exception or anything else.

raise ValueError("Incorrect Value")

Output:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    raise ValueError("Incorrect Value")
ValueError: Incorrect Value