1. Exception Handling in Python
Opening
Big idea: A useful program explains a failure and keeps control of what happens next.
Use a separate practice folder for the programs. Each example is self-contained unless its section says otherwise.
- Distinguish a syntax error, a runtime exception and a logic error.
- Read a traceback and use the exception type, its message and the line number.
- Use try, except, else and finally, and explain the job of each part.
- Catch specific built-in exception types, one at a time or in a group.
- Raise your own exceptions with clear messages to refuse impossible input.
- Decide between raise for input rules and assert for internal assumptions.
- Build a small program that survives bad entries and keeps running.
Read the rule, trace the worked example, and try the quick check before reading its answers. When a result surprises you, change one input and explain the difference.
This is an original lesson following the listed syllabus topics. Examples, datasets, questions and diagrams were created for this edition.
Complete Python examples have Copy code and an external run link. First predict the output. Run the example, then change one input and explain what changed. The output box shows the expected result; it is not another program.
1.1 INTRODUCTION
A user may enter a word when your program expects a number. The program needs a plan for that situation. It can explain the problem and ask again. It should not pretend that the word was a valid number.
Think of checking a message before using it. First ask whether the program itself is written correctly. Then ask whether the particular input can be used. Finally, ask whether the answer makes sense. These checks find different kinds of mistakes.
- A missing colon is a writing problem: Python cannot understand the statement.
- A failed conversion happens while an understood statement is being executed.
- A wrong formula may run successfully but still produce a wrong answer.
A user types “abc” into a box that asks for a page count. A good program explains the problem and asks again. A weak program crashes and loses the reader’s place. This chapter shows you how to build the good kind.
Programs meet problems in different ways, and each way needs a different response. An error is a problem in a program or in its execution.
Python sorts errors into groups, and the group decides what you can do about it.
A syntax error breaks the rules of the language, so the program cannot even start. A runtime exception interrupts an operation while the program is running, such as dividing by a zero count.
A logic error gives an incorrect result even though execution may finish normally.
The three groups need opposite habits. A syntax error asks you to repair the source text.
A runtime exception asks your program to respond to a situation it did not choose, such as a missing value. A logic error asks you to re-examine your own reasoning, because Python will never report it.
| Kind | Example | How to investigate |
|---|---|---|
| Syntax | A loop header has no colon. | Read the parser message and inspect the indicated line and the line before it. |
| Runtime exception | A program divides by a zero count. | Read the exception type, its message and the traceback. |
| Logic | An average divides by the wrong count. | Compare the formula and result with a small hand calculation. |
Read the table. The first row fails before any line runs, so investigate the text itself. The second row fails during execution, so read the report Python prints. The third row may print an answer and exit quietly, so only a comparison with a hand calculation exposes it. The right-hand column is your first move for each kind.
Predict the output before running this complete example.
marks = [80, 70, 90]
total = marks[0] + marks[1] + marks[2]
average = total / 2
print("Average:", average)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 creates the list marks with three values.
- Line 2 adds the three values and stores the sum in total.
- Line 3 divides total by 2. Dividing by 2 is legal, so no exception is raised.
- Line 4 prints the result and the program finishes normally. The printed answer is wrong, because there are three marks, not two.
Average: 120.0Change the divisor to len(marks). Predict the new printed line before you run the program, and explain why it is now correct.
A program that prints a wrong answer can look perfectly healthy. This one is the most dangerous of the three kinds.
It prints an answer, so it looks finished. A hand check exposes the mistake: the marks add up to 240 points, and 240 divided by 3 gives 80, not 120.
A program prints a negative distance after adding two positive distances. Must an exception have occurred?
Goal. Decide whether a wrong printed value proves that an exception was raised.
Approach. Ask whether every step was legal Python for the values it received.
Trace. Adding two positive distances is legal arithmetic and raises nothing. A reversed subtraction or a wrong variable can also print a negative number.
Check. Legal arithmetic plus a strange output points at the reasoning, not at a runtime failure.
Result: No. This may be a logic error; a successful run does not prove correctness.
When a program misbehaves, first reproduce the problem with a small input. Then identify which operation fails or which result first becomes wrong. Fixing becomes possible only after the failure is classified.
An exception is not always a defect in your work. A missing file can be a normal event in the world, because the user may not have created it yet.
A misspelled name in your own source is always a defect. Good programs expect the first kind and plan a response; they repair the second kind.
The three kinds also shape your testing. Run the file to expose syntax problems at once.
Feed the program difficult inputs, such as empty lists and missing files, to expose missing handlers. Compare printed results with small hand calculations to expose logic errors.
A program is finished only when all three checks pass.
A handler is useful only when it has a meaningful recovery action. Explaining the problem and asking again is recovery. Printing a vague message and continuing with broken data is not.
1.2 SYNTAX ERRORS
Python uses punctuation and indentation to recognise where a statement starts and what belongs inside it. A colon says that a block follows. The indented lines form that block. Missing either part can prevent Python from understanding the program.
Look at a loop in two pieces. Its header says which repetition to perform. Its body says what to do during each repetition. Reading these pieces separately is often easier than trying to understand the whole page at once.
- Locate the header and check its closing punctuation.
- Find the indented body and identify the lines that belong to it.
- If the parser points to a later line, inspect the earlier unmatched bracket, quote or block header too.
Python must understand the whole file before it can run the first line of it. One missing punctuation mark can stop every line, including lines that are themselves correct.
Before running a program, Python reads the source text and builds the internal plan that execution follows. This reading step is called parsing.
A syntax error occurs when source text cannot be parsed as Python, so the plan cannot be built and nothing runs at all.
Missing colons, unmatched brackets and badly formed statements are common causes. Indentation is also part of Python syntax.
A suite is the indented block of lines under a header such as for, if or while. Every line of one suite must use the same indent, because the indent tells Python which lines belong to the block.
Nothing runs until the whole file parses. This rule decides the order of your debugging. A report about a missing colon is about the file as a whole, not about one unlucky line.
Read the diagram. The journey begins when you save the file. Parsing reads the whole file and builds the run plan. The third and fourth rows are the two possible outcomes, not two steps in a row. A broken rule stops the parse, and Python reports a syntax error instead of running anything. A clean file passes the check and starts running from the first line.
for item in [2, 6]
print(item)The parser reports SyntaxError. Add the colon after the closing bracket to repair this example.
The report points at the position where reading became impossible. That position is a useful place to start, not always the exact place to repair.
Predict the output before running this complete example.
for item in [2, 6]:
print(item)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The list supplies one value at a time to item.
- The indented print belongs to the loop. It therefore runs once for each supplied value.
- After the last value has been printed, there are no more iterations.
2
6Replace one list value. Predict which output line changes.
A missing closing quote can push the report far from the real mistake. Python keeps reading to find a quote that never comes. Read the surrounding source rather than blindly changing the highlighted character.
Trace this program on paper first, then run it.
mark = 4
if mark < 5:
print("Low mark")
print("Ask for help")
print("Done")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores 4 in mark.
- Line 2 tests mark < 5. The condition is true, so the suite under the if runs.
- Lines 3 and 4 form that suite. Both print, in order.
- Line 5 is not indented, so it lies outside the suite and runs last.
Low mark
Ask for help
DoneChange mark to 7. Predict which lines print before you run the program, and explain why the block is skipped.
With no indented line under a header, Python reports an indentation error, which is a kind of syntax error. Mixing indent widths inside one suite also stops the parse. Choose one indent width and use it everywhere.
One more example shows why the pointer deserves careful reading. The program below forgot the closing quote, so the text of the string runs on and swallows the next line.
name = "Student A
print(name) File "quote.py", line 1
name = "Student A
^
SyntaxError: unterminated string literal (detected at line 1)The report names the file and line 1, shows the source, and places a marker where reading stopped. The final line names the problem: the string literal was never closed.
The marker sits under the first quote, but the repair is the missing second quote. The pointer and the repair do not always meet.
Older Python versions word some messages slightly differently. The meaning stays the same, and the shape of the report does not change: file, line, source, marker, then the type and message.
- Save and run often, so each new mistake appears alone.
- Read the final line of the report first: it names the problem.
- Then inspect the pointed line and the line before it.
- Check paired characters: quotes, brackets and colons.
- Repair one thing, and run the program again.
A try statement in an invalid source file cannot rescue that file from its own parsing failure. Parsing happens first, for the whole file.
Parsing separately supplied text with compile is a different situation: the running program can catch the SyntaxError raised by that operation.
try:
compile('for item in [2, 6]\n print(item)', '<lesson>', 'exec')
except SyntaxError:
print('SyntaxError')Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
SyntaxErrorThe outer file parses cleanly, so it can run. The text handed to compile is checked separately, and its SyntaxError arrives as an ordinary exception that the handler catches.
This is how a program can check other text, such as an entry typed by a user, without risking its own start-up.
1.3 EXCEPTIONS
Imagine reading a list position that is not present. The list itself may be valid. The indexing statement may also be valid Python. The problem appears only when that statement tries to use this particular position.
An exception changes the next step. Python stops the unfinished operation and looks for code that handles this kind of failure. Statements after the failing operation in the same try block are not a queue of jobs that Python automatically returns to.
- Read the statement that attempts the operation.
- Identify the exception type it raises for this input.
- Follow execution into a matching handler, then continue after the whole try statement.
A statement can be valid Python and still fail for a particular value. The list exists, the statement is legal, and the requested position is simply not there.
This section names that event and shows how a program takes control of it.
An exception is an object representing an unusual condition during execution. When an operation meets such a condition, it raises its exception. Raising stops the ordinary order of execution at once.
Python then looks for a handler: code written to respond to that kind of failure. A handler is chosen by type.
If no handler in the current block matches, the exception continues outward through the active calls. An exception that never finds a handler ends the program with a report.
Predict the output before running this complete example.
values = [11, 15]
try:
print(values[4])
print("after access")
except IndexError:
print("Choose an existing position")
print("finished")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Creating the list succeeds; the failure has not happened yet.
- The requested index is outside this list, so the indexing operation raises IndexError.
- Python skips the remaining statement in try and enters the matching handler.
- The final print is outside the try statement, so it still runs.
Choose an existing position
finishedUse an existing index and compare the path through the program.
Line 1 creates a list with two positions, numbered 0 and 1. Line 3 asks for position 4, which does not exist, so the access raises IndexError.
Line 3 cannot finish, and line 4, still inside try, is skipped entirely. Python jumps to the matching handler on line 5, which prints the friendly message.
Line 7 lies outside the try statement, so it runs in the ordinary order.
Trace the two routes once more. On success, lines 3 and 4 would have run, and the handler on line 5 would have been skipped.
On this failure, line 3 stops at the access, line 5 runs instead, and then line 7. Either way, line 7 always runs, because it is outside the try statement.
Read the diagram. The four boxes show one journey. The protected operation starts in the first box. Something raises an exception, so control leaves the ordinary path at once. The third box is the search for a handler whose type matches the raised class. The last box is the first ordinary statement after the whole try statement, where both the handled path and the success path meet. The failed operation is not retried automatically.
If a handler itself raises an exception, that new failure also needs handling somewhere. Adding try does not make arbitrary code immune to errors.
When no handler matches, Python stops and prints a traceback: a report of the route the program travelled and the failure it met. The word traceback means the path of calls, printed from the outermost call down to the failure.
print("Reading mark")
mark = 90
count = 0
average = mark / count
print("Average:", average)Traceback (most recent call last):
File "marks.py", line 4, in <module>
average = mark / count
~~~~~^~~~~~~
ZeroDivisionError: division by zeroSave this program as marks.py and run it. The word Reading mark prints, because every line up to the division succeeds.
Then the division by zero raises an exception that nothing handles, and the program stops with this report.
Read a traceback from the bottom up. The last line names the type and gives a short message: ZeroDivisionError, division by zero.
The lines above it give the file name, the line number and the source text involved. Newer Python versions also mark the exact position with small symbols; older versions leave that row out.
The traceback is evidence, not blame. It tells you which operation failed and where to start reading. The next section organises the common types, so the name itself becomes your first clue.
Work one more trace on paper before moving on. The program below reads a small record of stock levels. It looks up one key that exists and one that does not.
Read the program and predict every line of output.
stock = {"pen": 4}
try:
print(stock["pen"])
print(stock["clip"])
print("done")
except KeyError:
print("missing item")
print("order checked")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 creates the record with one key, pen.
- Line 3 looks up pen. The key exists, so 4 prints.
- Line 4 looks up clip. No such key exists, so the lookup raises KeyError.
- Line 5 is skipped, because control left the try suite at the failure.
- The handler prints missing item. The final line is outside the try statement, so it prints in the ordinary order.
4
missing item
order checkedChange "clip" to "pen" and predict the full output before running the program.
1.4 BUILT-IN EXCEPTIONS
Exception names are categories. They let you distinguish “this value cannot be converted” from “this position does not exist”. You do not need to memorise the full wording of every error message to understand that distinction.
Ask what the operation expected. Was the input the wrong type, the wrong value, a missing key or an unavailable file? That question connects the exception name to the cause instead of turning the table into a vocabulary exercise.
- Name the operation, such as conversion, division or indexing.
- Compare its requirements with the actual supplied input.
- Choose the exception category that describes the mismatch.
Python gives every failure a short name, such as ValueError or IndexError. The name describes the category of the problem. Learn the common names once, and every future traceback becomes faster to read.
The common failure types are built-in exception classes that come with the language. When an operation fails, Python raises an object of one of these classes.
The class name appears in the traceback, and a handler can name the class it is prepared to fix.
| Exception | Typical cause |
|---|---|
| ValueError | A suitable kind of input has an unacceptable value, such as int("many"). |
| TypeError | An operation receives an unsuitable type, such as adding a string to an integer. |
| ZeroDivisionError | Division or remainder uses a zero divisor. |
| IndexError | A sequence index is outside its valid range. |
| KeyError | A requested mapping key is absent. |
| NameError | A name cannot be resolved. |
| FileNotFoundError | An expected file path cannot be found. |
| AssertionError | An enabled assertion condition is false. |
Read the table. Work down the rows once, slowly. ValueError means the kind of value was suitable, but this value is not usable. The text "many" is a string, so the kind fits int, yet its contents are not a whole number. TypeError means the kind itself is wrong, as when text is added to a number. ZeroDivisionError, IndexError and KeyError describe arithmetic, sequence and mapping failures. NameError means a name was used before any value was assigned to it. FileNotFoundError means the path could not be opened. AssertionError belongs to the assert statement in section 1.5.
All of these classes descend from one parent class called Exception. The family matters in two ways.
A handler for a specific class catches exactly that failure and nothing else. A handler for Exception catches most failures, which is powerful and dangerous; it does not catch everything, because a few urgent events such as the user pressing the interrupt key sit above the family.
When you mix broad and narrow handlers, write the narrow ones first.
Predict the output before running this complete example.
text = "abc"
try:
mark = int(text)
except ValueError as error:
print("Problem:", error)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 3 converts the text. The text "abc" has no whole-number reading, so int raises ValueError.
- The rest of the try suite is skipped, and the conversion never produced a value.
- Line 4 catches ValueError only, and binds the exception object to the name error.
- Line 5 prints the message. Python explains the failed conversion in those exact words.
Problem: invalid literal for int() with base 10: 'abc'Change the text to "42" and predict the output. The handler does not run, and nothing prints at all, because there is no else suite yet.
The second familiar failure is a file that is not there. A reading program should say so clearly instead of crashing.
Trace this program on paper first, then run it.
try:
stream = open("missing.txt")
print(stream.read())
except FileNotFoundError:
print("No file named missing.txt")Copy the code, open the playground, and paste it into the console. Files are temporary browser files.
- Line 2 tries to open missing.txt for reading.
- No file with that name exists, so open raises FileNotFoundError before any reading happens.
- The handler prints a short explanation instead of letting the program stop with a traceback.
No file named missing.txtCreate an empty file with that name beside the program and run again. Opening now succeeds, and the read prints an empty line.
Two more rows of the table deserve their own examples, because they name mistakes every beginner meets.
A TypeError appears when an operation receives a kind of value it cannot use. Text and numbers look similar on the screen, but addition treats them differently.
Read the program and predict every line of output.
age_text = "17"
try:
print(age_text + 1)
except TypeError:
print("Convert the text to a number first")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 stores text. The quotes matter: age_text is a string, not a number.
- Line 3 tries to add a number to a string. Addition has no rule for that pair, so it raises TypeError.
- The handler prints the advice in one short line.
Convert the text to a number firstChange the print line to print(int(age_text) + 1) and predict the output before running.
A NameError appears when a name is used before any value was assigned to it. Most often the cause is a spelling slip: the variable exists, but this line wrote it differently.
Predict the output before running this complete example.
try:
print(total_marks)
except NameError:
print("No value has that name yet")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 2 asks for the name total_marks. Nothing was ever assigned to it in this program.
- Python cannot resolve the name, so it raises NameError.
- The handler prints a short reminder to check every spelling.
No value has that name yetAdd the line total_marks = 90 above the try statement and predict the output before running.
Predict the output before running this complete example.
checks = [lambda: int("many"), lambda: 9 / 0, lambda: {}["page"]]
for check in checks:
try:
check()
except (ValueError, ZeroDivisionError, KeyError) as error:
print(type(error).__name__)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Each lambda is a small function whose operation is postponed until check() calls it.
- The loop calls one function inside try, so a failure does not prevent the later test functions from being called.
- The handler catches only the listed error types and prints the name of the type that actually occurred.
ValueError
ZeroDivisionError
KeyErrorChange the invalid numeric text to valid digits and see which error disappears.
When two or more types need the same recovery, one handler can list them in a tuple, as line 5 does here. The name of the class that actually occurred is still available, because type(error).__name__ holds it.
The handler prints three different names from one clause.
The table gives typical cases, not every way these classes can arise. Use the actual operation and traceback to decide what went wrong.
A message can include details such as a missing key or file path, so read the message after the type.
1.5 RAISING EXCEPTIONS
A function is allowed to refuse an input it cannot use correctly. For example, a rate calculation needs a positive time period. Raising an exception says, “I cannot produce the promised result for this request.” That is clearer than returning a made-up answer.
An assertion has a different audience. It tells the programmer that an internal assumption has failed. An input rule belongs in ordinary validation because it must remain active whenever the application runs.
- Write down the input condition the function requires.
- Check that condition before using the input in a calculation.
- Raise a suitable exception if the requirement is not met; let the caller decide how to explain or recover.
Given zero days, the honest answer is “no result”, not a made-up number. Python lets your function refuse the request loudly and in its own words. This section shows the two tools for saying no, and when each belongs.
Use raise to signal an exception deliberately. Writing raise creates an exception object and starts it on the same journey as any built-in failure.
It interrupts the current suite at once and looks for a handler. Writing raise ValueError alone also works; Python then builds the object for you.
Pick a class that describes the violated condition, and give a short message in plain words. Raising does not handle anything by itself.
The caller still needs a matching handler to continue gracefully, or the whole program stops with a traceback.
Predict the output before running this complete example.
def pages_per_day(pages, days):
if days <= 0:
raise ValueError("days must be positive")
return pages / days
try:
pages_per_day(72, 0)
except ValueError as error:
print(error)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The function checks the day count before attempting division.
- The shown call supplies a zero day count. The condition is true, so raise ends that call with ValueError.
- The caller catches that exception and prints its message. No daily-rate result was produced.
days must be positiveSupply a positive day count and print the returned value.
The function checks the day count before attempting the division. If the check were missing, dividing by 0 would raise ZeroDivisionError with a mathematical message instead of your practical one.
Checking first lets you choose both the class and the wording.
Read the diagram. The journey begins inside the function. The guard finds input it cannot use, and raise starts the exception at that exact point. Python then walks outward through the callers, searching for a handler whose class matches. The last two rows are the two possible endings, not two steps. A match runs the recovery suite in the caller. No match ends the program with a traceback report.
Trace this program on paper first, then run it.
def average_mark(marks):
if len(marks) == 0:
raise ValueError("marks list is empty")
return sum(marks) / len(marks)
for batch in [[8, 9], []]:
try:
print(average_mark(batch))
except ValueError as error:
print("Cannot compute:", error)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The loop calls the function twice. The first batch holds two values, so the guard passes.
- Line 4 computes the sum divided by the length, and the first output line shows the result.
- The second batch is empty, so the guard is true and line 3 raises ValueError with its message.
- The call ends at the raise. Control moves to the handler in the loop, which prints the rejection with the message text.
8.5
Cannot compute: marks list is emptyAdd a third batch [5] to the loop and predict the line it adds. Explain why no handler runs for it.
A raise ends the function at that point. No line after it runs, unless a caller catches the exception and continues. This is why the raise belongs before the calculation it protects.
One function can guard several rules, and each rule deserves its own message. The function below refuses an impossible page request in two different ways.
Read the program and predict every line of output.
def open_page(total_pages, page):
if page < 1:
raise ValueError("page must be 1 or more")
if page > total_pages:
raise ValueError("page is beyond the end")
return page
for request in [0, 9, 4]:
try:
print("Opened page", open_page(8, request))
except ValueError as error:
print("Rejected:", error)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The loop makes three requests to a book of 8 pages.
- The request 0 fails the first guard, so the raise ends that call with the first message.
- The request 9 passes the first guard but fails the second, so the second message is raised.
- The request 4 passes both guards, and the function returns normally.
- Each printed line shows either the rejection or the opened page, with no overlap.
Rejected: page must be 1 or more
Rejected: page is beyond the end
Opened page 4Add the request 8 to the loop and predict the printed line before running.
When such a raise is never caught, the traceback of section 1.3 appears with your message after the class name. A clear message therefore serves two readers at once: the handler that prints it, and the programmer who reads the traceback.
An assertion checks an assumption made by the programmer. Write assert, then a condition, then an optional message after a comma.
If the condition is false while assertions are enabled, Python raises AssertionError carrying that message.
Assertions can be disabled in optimised execution, so they must not be the only validation for user input or permissions. A rule that must always hold needs a normal conditional and raise.
Predict the output before running this complete example.
ordered = [3, 7, 12]
assert ordered == sorted(ordered), "sorting failed"
print("assumption checked")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- sorted builds an ordered result for comparison.
- The assertion compares that result with the current list.
- The condition is true here, so execution reaches the success message.
assumption checkedMove the first list entry to the end. Observe the assertion failure, then explain why it is an internal check.
Predict the output before running this complete example.
marks = [7, 8, 9, 6, 5]
try:
assert len(marks) < 5, "marks list is full"
print("space left")
except AssertionError as error:
print("Check failed:", error)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 3 makes a promise: fewer than five marks. The list already holds five values, so the promise is false.
- assert raises AssertionError and attaches the message written after the comma.
- The handler prints that message after its own label.
Check failed: marks list is fullChange the list to hold three values and predict the output. The promise holds, so the handler never runs.
In a finished program you would normally repair this kind of bug, not catch the assertion. The example catches it only to show the exact report that a failed assertion produces.
Use a normal conditional followed by raise for a rule that must always be enforced. Use assert for an internal condition whose failure means the implementation itself needs investigation.
Raise enforces the rule; assert checks an assumption.
1.6 HANDLING EXCEPTIONS
A try statement gives one operation a controlled place to fail. Its except branch describes what to do when the named failure occurs. Its else branch describes what to do when that operation succeeds.
Picture two routes through a small decision. A successful conversion produces a number that can be used. A failed conversion produces no such number. The failed route must therefore retry, stop or skip the work that depends on it.
- Put only the operation you understand inside try.
- In except, restore a usable state or clearly stop the dependent work.
- In else, use the result that exists because the protected operation succeeded.
A reading tracker accepts entries from many users. Some entries are clean and some are not. The tracker should accept the clean ones, explain the rest, and keep running for the next entry.
Put the risky operation in try. Add an except clause naming the relevant exception.
Use as to bind the exception object when its details are needed. Put specific subclasses before broader classes because Python uses the first matching handler.
Read the diagram. The protected operation starts in the first box. The second row asks the only question that matters here: did something raise inside the try suite? The next two rows are alternatives, so one attempt passes through exactly one of them. A failure takes the except suite. A clean attempt takes the else suite. The last row belongs to both: ordinary execution continues after the whole statement.
Predict the output before running this complete example.
for text in ["18", "none"]:
try:
pages = int(text)
except ValueError:
print("Please enter a whole number")
else:
print("Accepted", pages)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The loop tests each text value separately.
- The valid conversion reaches else, where pages is available.
- The invalid conversion jumps to except. The successful-only print is skipped for that entry.
Accepted 18
Please enter a whole numberTry a negative whole-number string. Conversion can succeed even when the application should reject the value.
Follow each entry on its own route. The entry "18" converts on line 3 without trouble, so the handler is skipped and the else suite prints Accepted 18.
The entry "none" raises ValueError on line 3, so Python jumps to line 5 and prints the helpful message. For that entry the else suite never runs.
The optional else suite runs when the try suite completes without raising an exception. It separates the successful continuation from the operation that the handlers are meant to protect.
An exception raised in else is not caught by the except clauses attached to this same try.
Why not write the success code inside try instead? Two reasons.
First, a smaller try suite protects only the operation you understand, so an unrelated failure cannot be caught by mistake. Second, work placed in else runs only when the protected operation succeeded, which makes the intent obvious to a reader.
The program below is the reading-tracker pattern in miniature. It keeps a list of raw entries and makes one fresh attempt per entry. Bad text earns a clear rejection, and accepted values are collected in one list.
Trace this program on paper first, then run it.
entries = ["15", "abc", "12"]
accepted = []
for text in entries:
try:
mark = int(text)
except ValueError:
print("Rejected:", text)
else:
accepted.append(mark)
print("Accepted marks:", accepted)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 1 supplies the raw entries, as if a user had typed them one by one.
- The first entry converts cleanly, so else appends 15 to accepted.
- The second entry raises ValueError. The handler prints the rejection, and the entry is not added.
- The third entry converts cleanly and is appended as well.
- Line 10 runs after the loop and prints the collected list in one line.
Rejected: abc
Accepted marks: [15, 12]Add the entry "20" to the list and predict the final printed list before you run the program.
One bad entry never spoils the others. Notice what the handler does not do. It does not invent a mark, and it does not stop the loop. Each entry starts a fresh attempt, so the batch stays safe.
The same shape extends to counting. A tracker that summarises a batch needs two counters instead of one list. The version below counts accepted and rejected entries, and it also hides a small surprise: the empty entry.
Read the program and predict every line of output.
entries = ["8", "bad", "9", "", "10"]
good = 0
bad = 0
for text in entries:
try:
mark = int(text)
except ValueError:
bad += 1
else:
good += 1
print(good, "accepted,", bad, "rejected")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The list holds five raw entries, including one that is completely empty.
- The entries "8", "9" and "10" convert cleanly, so good rises to 3 in the else suite.
- The entries "bad" and "" both fail the conversion. An empty text is not a number either, so the handler counts both in bad.
- The final print runs after the loop and reports both counts in one line.
3 accepted, 2 rejectedAdd the entry "9x" to the list and predict both counts before running.
A real tracker can go one step further and ask again instead of counting a rejection. The pieces you have already written make that possible: the handler explains the problem, and a loop can present the question once more.
A handler prints “invalid entry” and then uses a result that was never assigned. What should change?
Goal. Decide what a handler must never do with a result it did not produce.
Approach. Follow the data. On the failure path, the assignment inside try never ran.
Trace. After printing the rejection, the handler reaches a line that reads the value. The name does not exist on this path, so a new failure follows the first one.
Answer. The failure path must not pretend a result exists.
Result: Keep the successful calculation in else, or return from the handler.
A tuple of exception classes can share one handler when the recovery action is the same, as you saw in section 1.4. Avoid an empty except that quietly hides every problem.
Catching an expected conversion error is different from hiding a programming defect.
1.7 FINALLY CLAUSE
Some actions must happen when an attempt ends: closing an owned resource or recording that an attempt is complete. Those actions are cleanup. They are different from deciding whether a failed calculation should be retried.
Finally is a place for ordinary cleanup as Python leaves a try statement. It can run after success or after a failure. The fact that it runs on both paths does not mean both paths produced a valid result.
- Identify what the attempt acquired or started.
- Choose the success or failure response in the appropriate branch.
- Put shared cleanup in finally, or use a resource-specific with statement when available.
Recovery and cleanup are different jobs. Recovery decides what to do next.
Cleanup releases what the attempt took hold of, such as an open file or a borrowed record. Python gives cleanup a room of its own, and that room runs on every path.
The finally suite is used for cleanup when control leaves the try statement through normal completion or Python exception handling. It also runs during ordinary returns.
It is not a guarantee against sudden process termination or loss of power.
Why does the language promise this? A resource acquired before the attempt must be released after it, whatever the outcome.
If cleanup sat only on the success path, every failure would leak it. Finally lets you write the release once, and Python keeps the promise on every ordinary exit.
Predict the output before running this complete example.
for divisor in [3, 0]:
try:
print(21 // divisor)
except ZeroDivisionError:
print("Cannot divide")
finally:
print("attempt complete")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Each loop iteration starts a new division attempt.
- A nonzero divisor reaches the numeric print; a zero divisor enters the handler.
- Finally prints its completion message after either path.
7
attempt complete
Cannot divide
attempt completeUse only nonzero divisors. Explain why the finally messages still appear.
Follow both attempts. First attempt: line 3 computes the whole-number division and prints 7.
The handler is skipped, and finally prints its line on the way out. Second attempt: the divisor is 0, so line 3 raises ZeroDivisionError.
The handler prints Cannot divide, and finally still prints its line. The loop then starts the next attempt with a clean slate.
Finally does not itself make a failed operation succeed or suppress an exception. It records the end of the attempt; the handler decides what the failure meant.
Predict the output before running this complete example.
def convert(text):
try:
number = int(text)
except ValueError:
print("except: not a number")
else:
print("else: got", number)
finally:
print("finally: attempt finished")
convert("5")
convert("x")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The call convert("5") converts cleanly. The except suite is skipped, so its message never prints.
- else runs for the success and prints the converted value.
- finally runs on the way out of the call, after else.
- The call convert("x") raises ValueError inside try. The handler prints its message this time.
- else is skipped for this call, but finally still prints its line before the function ends.
else: got 5
finally: attempt finished
except: not a number
finally: attempt finishedAdd a third call convert("7") and predict the three lines it adds.
Read the diagram. The first box is the protected operation. From there the journey splits, and the two middle rows are alternatives, not steps that both run. A matching failure takes the except row; a clean attempt takes the else row. Either way, control passes through the finally row before the last box, which is ordinary execution after the whole statement. Read the rows top to bottom, and remember that only one of the two middle rows belongs to any single attempt.
Finally also runs when no handler matches and the exception is still on its way out. This small program shows the order:
Trace this program on paper first, then run it.
try:
try:
print(5 / 0)
finally:
print("inner finally ran")
except ZeroDivisionError:
print("outer handler caught it")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- Line 3 raises ZeroDivisionError. The inner try has an except clause nowhere, only finally.
- Before the exception may leave the inner statement, its finally suite runs. That prints the first line.
- The exception continues outward to the outer try, whose handler catches it and prints the second line.
inner finally ran
outer handler caught itReplace the zero with 2 and predict the output. The inner statement finishes normally, and the outer handler is not needed.
Finally also earns its place when an attempt must be counted or recorded. The reading tracker below counts every attempt, whatever the outcome, which is exactly the kind of bookkeeping that must not depend on success.
Read the program and predict every line of output.
attempts = 0
for divisor in [4, 0, 2]:
try:
print(20 // divisor)
except ZeroDivisionError:
print("Zero divisor")
finally:
attempts += 1
print("Attempts:", attempts)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The loop makes three division attempts.
- The first attempt prints 5. The handler is skipped, and finally raises the count to 1.
- The second attempt raises ZeroDivisionError. The handler prints its message, and finally still raises the count to 2.
- The third attempt prints 10, and the count reaches 3.
- The final print shows the total number of attempts, whatever their outcomes were.
5
Zero divisor
10
Attempts: 3Move attempts += 1 into the except suite only, and predict the final count before running.
The promise also holds when the try suite ends with return. Python first runs finally, and only then does the function hand the value back. Cleanup written in finally therefore happens on the success path too.
Avoid return statements in finally: they can replace an earlier return or suppress a pending exception, making the real outcome hard to understand. For files, a with statement usually expresses cleanup more clearly than manual closing in finally.
Continue only after you have restored a usable state. A calculator can ask for a new divisor; a file importer may need to discard a partial record. “Carry on” is not a recovery plan unless later code has valid inputs.
Summary
Use these points to test what you can explain without looking back.
- Classify the failure before choosing a remedy: syntax, runtime exception, or wrong logic.
- A syntax error stops parsing. The whole file must be valid before any line of it runs.
- An exception is an object raised by a failing operation. A handler matched by type chooses the next action.
- A traceback lists the route of calls, the file and line, and the class and message of the failure.
- Built-in names such as ValueError, TypeError, ZeroDivisionError, IndexError, KeyError, NameError and FileNotFoundError describe categories of failure.
- raise signals a failure deliberately. assert checks an internal assumption and can be disabled in optimised runs.
- Catch specific exceptions close to the operation you understand. Group types in a tuple only when the recovery is shared.
- else contains the successful continuation. An exception raised in else needs an outer handler.
- finally handles cleanup and runs on every ordinary path out of the try statement.
- Keep try suites small, and test normal inputs, boundary inputs and deliberate failures.
Exercise
Work independently. For a program, predict the result before running it. Explain your reasoning as well as giving an answer.
1.1 A program accepts an empty list and then divides by its length. Classify the failure and name the exception type.
1.2 A loop header is missing a colon. Can a handler in that same invalid file fix the parsing failure?
1.3 Design a validation rule for a negative file size inside a function that receives it.
1.4 Explain why a handler for Exception should follow, not precede, a handler for ValueError.
1.5 A try suite succeeds, but its else suite raises an exception. Will the except clauses attached to this same try catch it?
1.6 Describe a safe response when int conversion of a user entry fails.
1.7 When would you prefer with over manual cleanup in finally?
1.8 Why is “catch everything and continue” a poor default?
1.9 Predict the full output of this program, then explain each printed line.
Predict the output before running this complete example.
raw = ["6", "x", "9"]
total = 0
for text in raw:
try:
total += int(text)
except ValueError:
print("Skipped:", text)
print("Total:", total)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The first entry converts and adds its value to total, so no message prints.
- The entry "x" raises ValueError, so the handler prints Skipped: x and the loop moves on.
- The entry "9" converts and brings the total to 15.
- The final print runs after the loop and shows the total in one line.
Skipped: x
Total: 15Change "x" to "1" and predict the new total before running.
1.10 A handler catches ValueError and then prints the variable that try was supposed to assign. What goes wrong on the failure path, and what is the repair?
1.11 Predict every line printed by this program, in order.
Trace this program on paper first, then run it.
for value in ["4", "abc", 0, "2"]:
try:
number = int(value)
print(20 / number)
except ValueError:
print("Bad text")
except ZeroDivisionError:
print("Zero divisor")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The entry "4" converts, and the division prints its result.
- The entry "abc" raises ValueError, and the first handler prints its message.
- The entry 0 is already a number, so conversion succeeds and the division raises ZeroDivisionError for the second handler.
- The entry "2" converts, and the division prints the last line.
5.0
Bad text
Zero divisor
10.0Move the division print into an else suite and explain what changes in the output.
1.12 Write a function price_per_unit(total, count) that raises ValueError("count must be positive") when count is not positive. Call it for the requests 40 with 4, and 40 with 0, printing the result or the rejection.
1.13 A program saved as grades.py holds two lines: values = [12, 7] and print(values[5]). The run stops with this report. Name the exception type, the line involved, and the message.
values = [12, 7]
print(values[5])Traceback (most recent call last):
File "grades.py", line 2, in <module>
print(values[5])
~~~~~~^^^
IndexError: list index out of range1.14 A teammate writes assert pages > 0 at the start of a function that must reject a zero page count. Give two reasons why raise is the better tool here.
1.15 One expression reads values[9] from a three-item list. Another reads record["name"] from a record that has no such key. Name the exception each raises, and explain why the two classes are different.
1.16 State the order in which try, except, else and finally run on (a) a successful attempt and (b) a failure that matches a handler.
1.17 A program reads a configuration file that the user may have deleted. Which kind of failure is this, and should the program treat it as a defect? Name the exception type and give one sensible recovery.
1.18 Predict every line printed by this program, in order.
Predict the output before running this complete example.
for text in ["4", "x"]:
try:
number = int(text)
except ValueError:
print("except:", text)
else:
print("else:", number)
finally:
print("finally")Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The first entry converts cleanly. except is skipped, else prints the value, and finally prints its line.
- The second entry raises ValueError. except prints its message, else is skipped, and finally still prints its line.
- Each entry passes through finally exactly once, whatever happened before it.
else: 4
finally
except: x
finallyAdd the entry "2" to the list and predict the three new lines before running.
Answers
1.1 The division raises ZeroDivisionError at runtime. The missing empty-input policy is a design problem that validation should have caught before the division ran.
1.2 No. The source must first be valid Python. Catching an error from separately compiled text with compile is a different situation.
1.3 Check the value with an if statement and raise ValueError when it is negative. Do not rely only on assert, which optimised runs can disable.
1.4 ValueError is an Exception subclass. Python uses the first matching handler, so a preceding broad handler would swallow ValueError failures too.
1.5 No. An exception raised in else needs a handler outside this try statement.
1.6 Catch ValueError from the conversion, explain the accepted format, and retry or stop before using the missing result. Never continue as if a value existed.
1.7 When the resource supports the context-manager protocol, such as an open file. with closes it on every ordinary exit, including an exception exit.
1.8 A broad handler can hide defects and continue with invalid state. Recovery must establish usable state, or stop clearly.
1.9 Skipped: x, then Total: 15. Only the entry "x" fails the conversion, so the handler reports it while 6 and 9 still add into the total.
1.10 On the failure path the assignment never ran, so reading the variable raises NameError. Move that use of the value into else. Or let the handler retry or stop, instead of using a value it does not have.
1.11 The lines print in this order: 5.0, Bad text, Zero divisor, 10.0. Each entry gets its own attempt, and the two handlers cover different types.
1.12 The guard checks count before the division and raises with the message. The caller catches ValueError and prints it; the first request prints 10, the second prints the rejection.
Read the program and predict every line of output.
def price_per_unit(total, count):
if count <= 0:
raise ValueError("count must be positive")
return total / count
for request in [[40, 4], [40, 0]]:
try:
print(price_per_unit(request[0], request[1]))
except ValueError as error:
print("Rejected:", error)Opens in a new tab with the code ready. Click Visualize Execution, then step through the program.
- The first request passes the guard, and the division prints 10.
- The second request trips the guard, so the raise ends that call at once.
- The handler prints the rejection with the exact message from the raise.
10.0
Rejected: count must be positiveAdd a request with a negative count and predict the printed line.
1.13 The type is IndexError, the line is line 2, and the message is list index out of range. The list has positions 0 and 1, so position 5 does not exist.
1.14 First, optimised runs can disable assertions, so the rule could vanish. Second, AssertionError reports a broken internal assumption, not an input rule; ValueError with a message describes the rejected request correctly.
1.15 IndexError for the list position, KeyError for the mapping key. Both mean the requested item is absent, but the classes differ, so a handler can treat them separately.
1.16 (a) try, then else, then finally. (b) try up to the failing operation, then except, then finally. else never runs on the failure path.
1.17 A runtime exception, not a defect. FileNotFoundError describes a missing file in the world outside the program.
A sensible recovery is to report the missing file clearly, then offer default settings or a fresh start.
1.18 The lines print in this order: else: 4, finally, except: x, finally. else runs only for the success, while finally runs for both entries.