Errors and exceptions
Overview
Things go wrong in every real program: users type letters where you expect numbers, files go missing, networks drop. When Python hits a problem it can’t continue from, it raises an exception. If nothing handles it, the program stops with a traceback. Exception handling lets you catch the problem, deal with it sensibly, and carry on.
What an exception looks like
age = int("twenty")Traceback (most recent call last):
File "app.py", line 1, in <module>
age = int("twenty")
ValueError: invalid literal for int() with base 10: 'twenty'The last line names the exception type (ValueError) and a message. Every exception is an object of a particular type.
try and except
Wrap the code that might fail in try, and say what to do if it does in except:
text = input("Age: ")
try:
age = int(text)
print(f"Next year you'll be {age + 1}")
except ValueError:
print("Please type a whole number.")
print("Program continues")- Python runs the
tryblock. - If a
ValueErrorhappens, it jumps straight to theexceptblock — the rest of thetryblock is skipped. - If no error happens, the
exceptblock is skipped. - Either way, the program carries on after the whole statement.
Combined with a loop, this gives robust input:
while True:
try:
age = int(input("Age: "))
break
except ValueError:
print("Please type a whole number.")Common exceptions
Exceptions form a family tree. except Exception would catch every error in the diagram — which sounds convenient, but it’s dangerous: it also hides bugs you didn’t expect, like a misspelled variable name. Catch the specific errors you expect and let real bugs show themselves.
Catching several exceptions
Several except blocks handle different problems differently; Python uses the first that matches:
try:
result = int(a) / int(b)
except ValueError:
print("Not a number")
except ZeroDivisionError:
print("Cannot divide by zero")To handle several types the same way, use a tuple:
except (KeyError, IndexError):
print("Not found")Using the exception object
as name gives you the exception itself, with its message:
try:
price = prices["pie"]
except KeyError as error:
print("Missing key:", error) # Missing key: 'pie'else and finally
The full form has two more optional parts:
elseruns only if thetryblock succeeded. Put the “everything worked” code here rather than in thetryblock, so thetrycontains only the line that can fail — then you won’t accidentally catch errors from other lines.finallyruns no matter what — success, handled error, unhandled error, evenreturnorbreak. Use it for clean-up such as closing connections.
try:
n = int(text)
except ValueError:
print("Not a number")
else:
print("Got", n)
finally:
print("Done")(For files, the with statement does the clean-up for you — see Reading and writing files.)
Keep try blocks small
# Too broad: which line raised the ValueError?
try:
age = int(input("Age: "))
height = float(input("Height: "))
bmi = weight / height ** 2
...
except ValueError:
print("Bad input")Wrap only the lines that can raise the error you’re handling. Small try blocks make it obvious what can go wrong and where.
Don’t silence errors
The worst pattern is catching everything and doing nothing:
try:
process(data)
except: # bare except — catches EVERYTHING, even Ctrl+C
pass # and hides itThe program carries on as if nothing happened, with wrong data, and you have no idea why. If you catch an error, handle it: show a message, use a default, retry, or log it. Never use a bare except:.
Asking forgiveness vs looking before you leap
Two styles exist:
# Look before you leap (LBYL)
if key in prices:
price = prices[key]
# Easier to ask forgiveness than permission (EAFP)
try:
price = prices[key]
except KeyError:
price = 0Python code often prefers the second style — especially for things you can’t check reliably in advance, like whether a file can be opened or whether text is a valid number. For simple cases, prices.get(key, 0) is better than either.
Rules: catch specific exceptions, keep
tryblocks small, put success code inelse, clean-up infinally— and never silence errors with a bareexcept: pass.
A calculator that never crashes
Write a loop that asks for two numbers and an operator (+, -, *, /) and prints the result. Use try/except so that: invalid numbers print Not a number: <text> and ask again; dividing by zero prints Cannot divide by zero; an unknown operator prints Unknown operator. Use else to print the result only when nothing went wrong. Typing q as the first number quits with Bye.
while True:
first = input("First number (q to quit): ")
if first == "q":
print("Bye")
break
second = input("Second number: ")
op = input("Operator: ")
# Convert, calculate and handle errorswhile True:
first = input("First number (q to quit): ")
if first == "q":
print("Bye")
break
second = input("Second number: ")
op = input("Operator: ")
try:
a = float(first)
b = float(second)
if op == "+":
result = a + b
elif op == "-":
result = a - b
elif op == "*":
result = a * b
elif op == "/":
result = a / b
else:
print("Unknown operator")
continue
except ValueError as error:
print("Not a number:", str(error).split(": ")[-1])
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result:", result)Summary
- An exception is Python’s way of signalling an error; unhandled, it stops the program with a traceback.
try:runs risky code;except SomeError:runs only if that error happens, and the program continues.- Catch specific exceptions (ValueError, KeyError, FileNotFoundError…), not everything.
elseruns only when the try block succeeded;finallyalways runs — use it for clean-up.except ValueError as error:gives you the exception object, with its message.