Python – Raise an Exception

Raise an Exception

In Python, we can raise an Exception using raise keyword. After raise keyword, pass the Exception object.

Examples

raise Exception()

In the following program, we are taking candidates for a job whose age is greater than or equal to 18. If the age is less than 18, we will raise an Exception with a message.

Python Program

age = 15

if age >= 18 :
    print('Candidate is eligible for the position.')
else :
    raise Exception('Candidate is under age.')
Run

Output

Traceback (most recent call last):
  File "example.py", line 6, in <module>
    raise Exception('Candidate is under age.')
Exception: Candidate is under age.

Summary

In this tutorial of Python Examples, we learned how to explicitly raise an exception using raise keyword, with the help of well detailed examples.