Raise Statement in Python
In Python, the 'raise' statement allows you to manually trigger an exception within your code.
Syntax
raise [expression]
Purpose
You can use it to deliberately cause the program to throw an error when a specific abnormal condition occurs.
In this case, the statement either propagates the last exception that was encountered or triggers a new error.
raise
Alternatively, you can invoke a specific exception to handle it within a try-except structure.
try:
raise error
except error:
...
Practical Examples
Here are some practical examples to illustrate how the 'raise' statement works in Python.
Example 1
In this script, I check the sign of the variable 'voto'.
If the number is negative, I artificially generate an error in the program.
- voto = -1
- if (voto < 0):
- raise "Negative value error"
- print(voto)
The program's output is:
Traceback (most recent call last):
File "Python36-32\tutorial.py", line 3, in <module>
raise "Negative value error"
TypeError: exceptions must derive from BaseException
The program errors out and stops. This prevents further processing if the error is serious.
This is useful when the error is severe and cannot be handled in other ways.
Example 2
In this example, I raise a TypeError on line 3 within the try block.
- try:
- print("1")
- raise TypeError
- except ZeroDivisionError:
- print("2")
- except TypeError:
- print("3")
The Python interpreter finds and executes the 'except TypeError' clause on line 6.
The script's output is:
1
3
Example 3
In this script, I pass arguments to the exception.
- try:
- print("1")
- raise Exception('4')
- except NameError:
- print("3")
- except Exception as e:
- print(e)
The program's output:
1
4
Example 4 (Exception Propagation)
In this example, I use 'raise' without specifying an exception on line 6.
- try:
- print("1")
- raise Exception('4')
- except Exception as e:
- print(e)
- raise
In this case, the 'raise' statement propagates the last exception, which is "4" (line 3).
The script's output is:
1
4
Traceback (most recent call last):
File "tutorial.py", line 3, in <module>
raise Exception('4')
Exception: 4
The program executes line 2 and raises the first exception on line 3.
Then it triggers the second exception on line 6, propagating the last exception (Exception('4')).
Since there are no other 'except' clauses to handle it, the script errors out.
And so on.