How to Throw an Exception If a Condition Occurs in Python


In this example we will show how to throw an exception if a condition occurs using the raise keyword in Python.

Source Code

 exception
num = 16

if num > 10:
    raise Exception("'num' can't be greater than 10. 'num' is: {}".format(num))

Output:

Traceback (most recent call last):
  File "demo.py", line 4, in 
    raise Exception("'num' can't be greater than 10. 'num' is: {}".format(num))
Exception: 'num' can't be greater than 10. 'num' is: 16
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments