Python try/except: catch the error before it wrecks your damn program
Updated · every example run on Python 3.9 to 3.15
By now Python has yelled at you plenty: NameError, KeyError, IndexError, that TypeError about adding a string to an int. Each time, the program stopped dead. That's the right call when the bug is yours. It's a terrible call when the problem is the outside world: someone types "forty" where you asked for a number, and your whole program falls over like a cheap folding chair.
This lesson is about both. First, reading the error properly, because it usually tells you exactly what's wrong. Then catching the errors you expected, so one bad input doesn't take everything else down with it.
Read a traceback from the bottom up
An error that nobody catches prints a traceback: the trail of function calls that were running when things went wrong.
def average(numbers):
return sum(numbers) / len(numbers)
def report(name, scores):
print(f"{name}: {average(scores)}")
report("Ada", [90, 85, 95])
report("Sam", [])Ada: 90.0
Traceback (most recent call last):
File "/home/me/project/main.py", line 8, in <module>
report("Sam", [])
~~~~~~^^^^^^^^^^^
File "/home/me/project/main.py", line 5, in report
print(f"{name}: {average(scores)}")
~~~~~~~^^^^^^^^
File "/home/me/project/main.py", line 2, in average
return sum(numbers) / len(numbers)
~~~~~~~~~~~~~^~~~~~~~~~~~~~
ZeroDivisionError: division by zero| Python | Prints |
|---|---|
| 3.9–3.15 | ZeroDivisionError: division by zero |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.
Ada's report works. Sam has no scores, so average divides zero by zero, and the whole thing goes to shit. Read the traceback from the bottom up:
- The last line is the error's type and message:
ZeroDivisionError: division by zero. Start here. Every damn time. - The entry just above it is where it happened:
line 2, in average, followed by the exact code that failed. - Everything above that is how you got there. "Most recent call last" means the oldest call is at the top: the file called
reporton line 8, andreportcalledaverageon line 5.
The bottom line tells you what broke, but the bug is often higher up. Dividing by len is fine; calling report with an empty list is the real problem. From Python 3.11 on, the traceback also draws marks under the code: ^ under the part that failed and ~ under the pieces around it, so on line 2 the ^ sits right under the /. Python 3.11 and 3.12 leave a line bare when the marks would only underline all of it, like the plain call on line 8; from 3.13 that line gets marks too. Python 3.9 and 3.10 show the code and leave the squinting to you.
try and except
Put the risky line in a try block. If it raises, Python skips the rest of the try and jumps to the except that names that error. Then the program carries on after the whole thing as if nothing happened.
ages = ["34", "29", "forty", "51"]
for text in ages:
try:
age = int(text)
print(f"{text}: turns {age + 1} next birthday")
except ValueError:
print(f"{text}: not a number, skipping")
print("Done, and nothing crashed")34: turns 35 next birthday
29: turns 30 next birthday
forty: not a number, skipping
51: turns 52 next birthday
Done, and nothing crashedWithout the try, int("forty") would end the program with ValueError: invalid literal for int() with base 10, and "51" would never get its birthday. With it, the bad value gets one line of complaint and the loop moves on. Notice the print inside the try didn't run for "forty": once int raised, the rest of the block was skipped.
Catch the right exception
except ValueError: catches a ValueError and nothing else. You can also write a bare except: that catches everything. It feels safe. It is a fucking trap:
prices = {"milk": 1.99, "eggs": 3.49}
def price_of(item):
try:
return prices[item]
except KeyError:
return 0
def price_of_sloppy(item):
try:
return prcies[item]
except:
return 0
print(price_of("milk"), price_of("caviar"))
print(price_of_sloppy("milk"), price_of_sloppy("caviar"))1.99 0
0 0price_of catches only the missing key, so milk costs 1.99 and caviar costs 0. price_of_sloppy has a typo, prcies, which raises a NameError every single time. The bare except swallows it, and now milk is free and Python never said a word. A bare except even catches you pressing Ctrl+C to stop the program. Name the error you expect, and let every other one crash loudly where you can see it.
When one block can fail in more than one way, use several except clauses, or one with a tuple of types. Add as err to get the error itself, which prints as its message:
try:
total = prices[item] * int(quantity)
except KeyError:
print("We don't sell", item)
except (ValueError, TypeError) as err:
print("Bad quantity:", err)
else and finally
A try can have two more blocks. else runs only if the try raised nothing. finally runs no matter what: success, a caught error, or an error that nobody catches.
def pay(balance, text):
try:
amount = int(text)
except ValueError:
print(f"'{text}' is not an amount")
else:
print(f"Paid {amount}, left: {balance - amount}")
finally:
print("Receipt printed")
pay(100, "40")
pay(100, "a lot")
pay("100", "40")Paid 40, left: 60
Receipt printed
'a lot' is not an amount
Receipt printed
Receipt printed
Traceback (most recent call last):
File "/home/me/project/main.py", line 13, in <module>
pay("100", "40")
~~~^^^^^^^^^^^^^
File "/home/me/project/main.py", line 7, in pay
print(f"Paid {amount}, left: {balance - amount}")
~~~~~~~~^~~~~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'int'| Python | Prints |
|---|---|
| 3.9–3.15 | TypeError: unsupported operand type(s) for -: 'str' and 'int' |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.
The first two calls go as planned. The third passes the balance as the string "100", so balance - amount in the else raises a TypeError. The except doesn't catch it, and it couldn't even if it named TypeError: errors raised in else aren't covered by the try at all. Look at the order, though: "Receipt printed" still appears before the traceback. finally ran on the way out.
That is what else is for: it keeps the try down to the one line you expect to fail, so you don't accidentally catch errors from the lines after it. And finally is for cleanup that must happen whatever goes wrong, like closing a file, which the next lesson does for you in a tidier way.
raise your own errors
Your own functions can complain too. raise creates an error and throws it at whoever called the function. It's like return, but for bad news.
def withdraw(balance, amount):
if amount <= 0:
raise ValueError(f"amount must be positive, got {amount}")
if amount > balance:
raise ValueError(f"not enough money: balance {balance}, asked for {amount}")
return balance - amount
balance = 100
for amount in [30, -5, 500, 50]:
try:
balance = withdraw(balance, amount)
print(f"Took {amount}, balance {balance}")
except ValueError as err:
print("Refused:", err)Took 30, balance 70
Refused: amount must be positive, got -5
Refused: not enough money: balance 70, asked for 500
Took 50, balance 20withdraw doesn't print anything and doesn't decide what happens next. It just refuses, with a message that says why, and the caller chooses: here, it reports and moves on to the next amount. If nobody had caught it, the program would stop with a traceback ending in your own message, which beats silently handing out 500 bucks nobody has.
Pick the built-in type that fits: ValueError when the type is right but the value is wrong, TypeError when the type itself is wrong. Inside an except, a bare raise throws the same error onward, which is handy when you want to print something and still let it crash. You can also invent your own error types, but that needs classes, which are lesson 13.
Try it yourself
Write a function safe_int(text, default=0) that returns int(text), or the default when the text isn't a whole number. safe_int("42") should give 42, safe_int("forty-two") should give 0, and safe_int("", default=-1) should give -1.
Show the answer
def safe_int(text, default=0):
try:
return int(text)
except ValueError:
return default
print(safe_int("42"))
print(safe_int("forty-two"))
print(safe_int("", default=-1))
It catches ValueError only. Hand it a list by mistake and it still crashes with a TypeError, which is exactly what you want: that one is your bug, not bad input.
Questions
What does "Traceback (most recent call last)" mean?
It is the list of function calls that were in progress when the error happened. The oldest call is at the top and the one that failed is at the bottom, right above the error's name and message.
How do I print the error message in a Python except block?
Name the error with as: except ValueError as err: and then print(err). Printing err gives the message, such as "invalid literal for int() with base 10: 'forty'".
How do I catch multiple exceptions in one except?
Put them in parentheses: except (ValueError, TypeError):. From Python 3.14 the parentheses are optional when there is no as, but on 3.13 and older leaving them out is a SyntaxError, so keep them while your code has to run anywhere else.
Is a bare except bad in Python?
Almost always. It catches every error, including typos in your own code and Ctrl+C, so bugs vanish instead of being reported. Catch the specific errors you expect; except Exception: is the widest you should usually go.
Sources
- Errors and exceptions, Python documentation
- Handling exceptions, Python documentation
- Raising exceptions, Python documentation
- Defining clean-up actions, Python documentation
- Built-in exceptions, Python documentation
- PEP 758: Allow except and except* expressions without parentheses, Python Enhancement Proposals
Read on November 11, 2026.