Python error handling (try + except + finally)
try to do something, except if it fails, then finally do something else!
2025-11-04 16:26
// updated 2025-11-06 20:56
// updated 2025-11-06 20:56
A script will "error out" in two different ways if "something goes wrong":
- silently failing
- the script continues to run but would yield unexpected or trivial output
- error handling
- the script stops running and explicitly explains what has happened
To allow flexibility in our Python code, we can use statements that "allow for failure":
try(to do something)except(if it fails, then do something else)finally(do some last thing in any case)
The try statement always accompanies an except, while a finally (which must accompany both try and except) remains optional!
Here, we shall look at an example that uses all three:
numbers = [ 'x', 'y', 'z' ]
# this list's values are not actually numbers so the code will "error out" to the except block
try:
print(x * y * z)
# multiplies the variables if they are numbers
except:
print("cannot print because the items are not numbers")
# if something goes wrong
finally:
print("thank you for using the app!")
# shows regardless of the outcomeA finally always executes whether the code goes inside the "try" or the "except" block!
Javascript: we might know the except statement as the "catch" statement!