PY-101 ยท Files and errors
try, except and finally
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
try runs code that might fail; if it raises an exception, the matching except block handles it instead of the program crashing. else runs when nothing failed, and finally always runs, error or not. Catch specific errors such as ValueError, not everything.
- Catch specific exceptions
- Use else and finally
- Keep a program running after bad input
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
for text in ["12", "twelve", "0"]:try:n = int(text)result = 100 / nexcept ValueError:print(text, "-> not a number")except ZeroDivisionError:print(text, "-> cannot divide by zero")else:print(text, "->", result)finally:print("checked", text)
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
12 -> 8.333333333333334
checked 12
twelve -> not a number
checked twelve
0 -> cannot divide by zero
checked 0 ๐ฏ Keep asking for an age until the input is a whole number, then print "Age: 30". The Input box has: abc, 3o, 30.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
while True: try: age = int(input("Age? ")); break, except ValueError: print("Try again")
- The problemA user types "twelve" where you expected 12. Without error handling the whole app crashes. With try/except it says "please type a number" and carries on.
- The Python idea
try:try runs code that might fail; if it raises an exception, the matching except block handles it instead of the program crashing. - In real lifePayment code wraps the call to the bank in try/except so a timeout shows "please try again" instead of an error page.
Start with a question
A user types "twelve" where you expected 12. Without error handling the whole app crashes. With try/except it says "please type a number" and carries on.
Real input is messy and networks fail. Handling errors is what separates a script from a product.
Explain it like I'm 10
try is "have a go". except is the safety net that catches you if you slip. finally is tidying up, whether you slipped or not.
The technical explanation
except ValueError: catches only ValueError. You can list several: except (ValueError, TypeError):.
except ValueError as e: gives you the error message in e.
else runs only if the try block succeeded; finally always runs, which is ideal for cleanup.
Syntax
try:
...
except SomeError as e:
...
else:
...
finally:
... Real-world scenario
Payment code wraps the call to the bank in try/except so a timeout shows "please try again" instead of an error page.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Raising and custom exceptions โQuestions people ask
What is the difference between an error and an exception in Python?
In everyday speech they mean the same thing. Technically, an exception is the object Python raises when something goes wrong, and you can catch it with except.
Should I use try/except or check with if first?
Python style often prefers "try it and handle the failure" (EAFP), especially for conversions and files, because the check and the action can drift apart.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between an error and an exception in Python?
In everyday speech they mean the same thing. Technically, an exception is the object Python raises when something goes wrong, and you can catch it with except.
beginner Should I use try/except or check with if first?
Python style often prefers "try it and handle the failure" (EAFP), especially for conversions and files, because the check and the action can drift apart.
intermediate When does except run?
When the try block raises a matching error. Only on a matching exception.
intermediate When does finally run?
Always. Error or not.
Quick revision
Remember
- Catch specific exceptions
- Use else and finally
- Keep a program running after bad input
- A bare
except:catches everything, including typos in your own code, and hides real bugs. Name the errors you expect.
Syntax
try:
...
except SomeError as e:
...
else:
...
finally:
... Official documentation
- Handling exceptions (docs.python.org)