githubEdit

Python Exceptions

Learn how exceptions work and how to handle them safely.

Exceptions are runtime errors that stop normal program flow. You can handle them with try and except.

Basic Example

try:
    value = int("abc")
except ValueError:
    print("Not a number")

Catch Multiple Exceptions

try:
    result = 10 / 0
except (ZeroDivisionError, TypeError):
    print("Bad operation")

else and finally

try:
    num = int("5")
except ValueError:
    print("Invalid")
else:
    print("Valid")
finally:
    print("Always runs")

Raising Exceptions

Next | Previous

Last updated