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.
| Block | Runs when… |
|---|---|
try | always tried first |
except | an error happened |
else | no error happened |
finally | always, 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/exceptfor 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.