Python Exception Handling

Python
try:
    x = int(input("Enter a number: "))
    print(100 / x)
except ValueError:
    print("That's not a number")
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("No error occurred")
finally:
    print("Done")
Enter a number: 0 Cannot divide by zero Done
BlockRuns when
tryAlways (code that may fail)
exceptA matching exception is raised
elseNo exception occurred
finallyAlways, even after return or an error

Raising Custom Exceptions

Python
class AgeError(Exception):
    pass

def vote(age):
    if age < 18:
        raise AgeError("Must be 18+")
    return "Eligible"

try:
    vote(16)
except AgeError as e:
    print("Error:", e)
Error: Must be 18+
Track your progress through the Python course