![]() |
VOOZH | about |
The raise keyword raises an exception and immediately stops the normal execution of the program. The control is then transferred to the nearest matching except block (if present), otherwise the program terminates.
Example: In below code, we check if a number is negative. If the number is negative, we raise an exception.
Output
Traceback (most recent call last):
File "c:\Users\gfg0753\practice 2.py", line 3, in <module>
raise Exception("Negative numbers are not allowed")
Exception: Negative numbers are not allowed
Below is the syntax of raise keyword:
raise ExceptionType("message")
The basic way to raise an error is:
raise Exception("user text")
In the below code, we check whether a number is odd or even. If the number is odd, an exception is raised.
Output
Traceback (most recent call last):
File "c:\Users\gfg0753\practice 2.py", line 3, in <module>
raise Exception("The number shouldn't be an odd integer")
Exception: The number shouldn't be an odd integer
We can check the type of error which have occurred during the execution of our code. The error can be a 'ValueError' or a 'ZeroDivisionError' or some other type of error. Below is the syntax:
raise TypeError
Example: In the below code, we try to convert a string into an integer. If conversion fails, we raise a ValueError.
Output
Traceback (most recent call last):
File "c:\Users\gfg0753\practice 2.py", line 3, in <module>
num = int(s)
ValueError: invalid literal for int() with base 10: 'apple'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\gfg0753\practice 2.py", line 5, in <module>
raise ValueError("String can't be changed into integer")
ValueError: String can't be changed into integer
When we use the raise keyword, there's no compulsion to give an exception class along with it. When we do not give any exception class name with the raise keyword, it reraises the exception that last occurred.
Example: In the below code, we catch an exception and re-raise it using raise without specifying the exception type.
Output
Traceback (most recent call last):
File "c:\Users\gfg0753\practice 2.py", line 3, in <module>
num = int(s)
ValueError: invalid literal for int() with base 10: 'apple'