Python | Exceptions | Raising Exceptions

You can raise exceptions by using the raise statement.

print(1)
raise ValueError
print(2)

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
1
Traceback (most recent call last):
  File "file.py", line 2, in 
    raise ValueError
ValueError
ddn_ro@linux:~/Desktop$

You need to specify the type of the exception raised.

Exceptions can be raised with arguments that give detail about them.

Example:

name = "123"
raise NameError("Invalid name!")

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Traceback (most recent call last):
  File "file.py", line 2, in 
    raise NameError("Invalid name!")
NameError: Invalid name!
ddn_ro@linux:~/Desktop$

In except blocks, the raise statement can be used without arguments to re-raise whatever exception occurred.

Example:

try:
	num = 5 / 0
except:
	print("An error occurred")
	raise

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
An error occurred
Traceback (most recent call last):
  File "file.py", line 2, in 
    num = 5 / 0
ZeroDivisionError: integer division or modulo by zero
ddn_ro@linux:~/Desktop$

Leave a Reply