else, finally and raise

else and finally

try:
    number = int("42")
except ValueError:
    print("Not a number")
else:
    print("Success! Double is", number * 2)
finally:
    print("This always runs.")

Output

Success! Double is 84
This always runs.
BlockRuns when…
tryalways tried first
exceptan error happened
elseno error happened
finallyalways, error or not – good for clean-up

Raising your own errors

Sometimes you want to stop because something is wrong. raise creates an error on purpose:

def set_age(age):
    if age < 0:
        raise ValueError("Age can't be negative")
    return age

try:
    set_age(-3)
except ValueError as error:
    print("Error:", error)

Output

Error: Age can't be negative

Remember: Use try/except for things outside your control – like what the user types or whether a file exists. Don't use it to hide bugs in your own code.

HOME LEARN COMMUNITY DASHBOARD