Python, lesson 9
Things go wrong in real programs: a user types ten where you expected a number, a file is
missing, someone divides by zero. Python reports these problems by raising an exception.
If nothing handles it, the program stops and prints a traceback. Handling exceptions lets
your program react sensibly instead of crashing.
Put the risky code in a try block and say what to do in an except block:
If int() fails, Python jumps straight to the matching except block; the rest of the try
block is skipped. If nothing fails, the except block is skipped.
Always name the exception type you expect. A bare would also swallow typos and other bugs you'd much rather see.
2 exercises to try what you just read.
except:| Exception | Typical cause |
|---|---|
ValueError | right type, bad value: int("abc") |
TypeError | wrong type: "3" + 4 |
ZeroDivisionError | dividing by zero |
IndexError | list index out of range |
KeyError | missing dictionary key |
FileNotFoundError | opening a file that isn't there |
They are all classes that inherit from Exception. An except clause also catches
subclasses of the type it names.
A try statement can have several except clauses, checked in order. You can also catch
several types in one clause. Since Python 3.14 the parentheses are optional when you don't
use as, but they work in every version:
as err gives you the exception object, whose text explains what went wrong. The else block
keeps the "success" code out of the try, so you don't accidentally catch errors from it.
finally is for cleanup that must always happen, such as closing a connection.
When your own function receives something it can't work with, raise an exception rather than returning a strange value. The caller then decides how to handle it:
For errors that belong to your program's own rules, define a class that inherits from
Exception. The class body can be empty; the name alone carries the meaning:
Callers can now write except OutOfStockError: and handle exactly that case while letting
anything unexpected through.
Python code often just tries the operation and handles the failure, instead of checking
every condition first. Converting text with int() inside try is simpler and more reliable
than inspecting each character yourself.
Each input line holds two values separated by a space. For each line, divide the first by the second and print the result with two decimals. Instead of crashing:
error: not a numbererror: division by zeroSample input:
Sample output:
The first line is the starting balance (a whole number). Each following line is either
deposit N or withdraw N. Write withdraw(balance, amount) so it raises the custom
exception InsufficientFunds when the amount is larger than the balance, and returns the new
balance otherwise. When a withdrawal fails, print declined: balance is B (with the current
balance) and carry on. At the end print final: B.
Sample input:
Sample output:
text = input()
try:
age = int(text)
print(f"Next year you'll be {age + 1}")
except ValueError:
print(f"'{text}' is not a whole number")try:
a, b = input().split()
result = int(a) / int(b)
except ZeroDivisionError:
print("Can't divide by zero")
except (ValueError, TypeError) as err:
print(f"Bad input: {err}")
else:
print(result) # runs only if nothing was raised
finally:
print("Calculation done") # runs no matter whatdef set_volume(level):
if not 0 <= level <= 10:
raise ValueError(f"volume must be 0-10, got {level}")
return levelclass OutOfStockError(Exception):
pass
def take(stock, amount):
if amount > stock:
raise OutOfStockError(f"only {stock} left")
return stock - amount10 4
7 0
abc 22.50
error: division by zero
error: not a number50
withdraw 20
withdraw 40
deposit 15declined: balance is 30
final: 45