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

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 outcome

A 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!

⬅️ older (in textbook-python)
🐍 Python functions
newer (in textbook-python) ➡️
Python classes and objects 🐍
⬅️ older (in code)
🐍 Python functions
newer (in code) ➡️
Python classes and objects 🐍
⬅️ older (posts)
🐍 Python functions
newer (posts) ➡️
Python classes and objects 🐍