To raise an exception in Python, use the raise keyword. The raise keyword creates a user-defined exception. We can create our exception using the Python raise keyword. Even though we can handle exceptions in try and except block, there are some errors that python does not handle. In that case, raising exceptions helps us to handle the error.
Python exception class has several exception classes. These exception classes can be handled using python try and except statements. But the error class that is not in the exception class cannot be handled using the try and except block. In those cases, we can use the raise keyword.
Program to raise an exception using try and except block
x = 50 y = 0 try: print(x / y) except ZeroDivisionError as e: print("You cannot divide any number by zero")
You cannot divide any number by zero
In this case, we used the try and except blocks. We can catch the exception using the exception class called ZeroDivisonError. We can do the same using the raise statement.
x = 50 y = 0 if(y == 0): raise Exception("ZeroDivisionError occured") else: print(x / y)
Exception: ZeroDivisionError occurred
In this program, we raised the error message for ZeroDivisionError. But the error message is our error message. We have used raise along with the exception to raise the user-defined exception. If the denominator is zero, this error message is raised using the raise keyword. If the denominator is not zero, the number x is divided by y.
We used the raised error message using the raise function, but this error can be handled using the try and except blocks. There is a class for zero division error; hence we can do using that. But there are some cases where we cannot use the try and except block.
Let’s see another example.
num = -10 if(num > 0): print("The number is positive") else: raise Exception("This program accepts only positive numbers")
Exception: This program accepts only positive numbers
In this program, we created a variable called num. First, we stored a value of -10. Then, in the if statement, we checked whether a number is greater than 0.
If the number is greater than zero, it is printed as the number is positive. However, as the number is -10, it is less than zero, so if the statement is not executed, the program comes to the else part. Here, the error is raised with the error message.
This error cannot be handled in the try and except block. Therefore, we have created our exception in this program.
That’s it for this tutorial.
Krunal Lathiya is an Information Technology Engineer. By profession, he is a web developer with knowledge of multiple back-end platforms including Python. Krunal has written many programming blogs which showcases his vast knowledge in this field.