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.
num = -3
if num < 0:
raise Exception("Negative numbers are not allowed")
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
Syntax
Below is the syntax of raise keyword:
raise ExceptionType("message")
The basic way to raise an error is:
raise Exception("user text")
Check Odd or Even Number
In the below code, we check whether a number is odd or even. If the number is odd, an exception is raised.
a = 5
if a % 2 != 0:
raise Exception("The number shouldn't be an odd integer")
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
Raise Specific Exception Type
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.
s = 'apple'
try:
num = int(s)
except ValueError:
raise ValueError("String can't be changed into integer")
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
Re-raising an Exception
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.
s = 'apple'
try:
num = int(s)
except:
raise
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'
Advantages
- Helps in stopping execution when an invalid condition occurs
- Allows custom error messages for better debugging
- Enables manual raising of exceptions when needed
- Useful for input validation and enforcing rules
- Supports re-raising exceptions for better error handling flow
