» Quick Introduction to Python » 1. Basics » 1.10 Exception Handling

Exceptions

Try Except

try:
    a = 1 / 0 # trigger the exception on purpose
except ZeroDivisionError:
    print("cannot divide by zero")

Multiple Excepts

try:
    a = int("NaN") # trigger the ValueError on purpose
    a / 0 # trigger the ZeroDivisionError on purpose
except ZeroDivisionError:
    print("cannot divide by zero")
except ValueError:
    print("invalid value for integer parsing")

Try Else

try:
    a = int("5")
    a / 10
except ZeroDivisionError:
    print("cannot divide by zero")
except ValueError:
    print("invalid value for integer parsing")
else:
    print("everything is ok")

Code Challenge

Try to modify the code provided in the editor to trigger the expected exception.

Loading...
> code result goes here
Prev
Next