LambdaLabTM
Computer Science · Class 12 · Exception Handling
ExceptionsThe idea⏱️ 13 min read

Errors & Exceptions

People use the two words as if they mean the same thing, and they nearly do. Every exception is an error — but not every error is an exception. The difference is when Python finds out, and it decides whether you can do anything about it.

1Class 11 sorted errors into three kinds

You met these already: syntax errors, run-time errors and logical errors. It is worth putting them side by side once more, because only one of the three is an exception.

Syntax error
Before the program starts

The file is not valid Python, so Python refuses to run any of it. Nothing at all happens — not even the lines above the mistake.

Run-time error
While the program is running

The file was fine. The program started, ran, and then hit something it could not do. THIS is what an exception is.

Logical error
Never — Python is happy

The program runs to the end and gives the wrong answer. No message, no traceback, nothing to catch. Only you can find it.

2A syntax error: nothing runs at all

syntax_error.py
print('this never appears')

if 10 > 5
    print('missing colon above')
Output
  File "syntax_error.py", line 3
    if 10 > 5
             ^
SyntaxError: expected ':'

Look at what is missing from that output. The print on the first line never ran, even though there is nothing wrong with it. Python reads the whole file before running any of it, found the file was not valid Python, and stopped there.

Key Takeaway
A syntax error is not something a running program can deal with, because there is no running program. The file never started. This is why no amount of exception handling will help you with a missing colon — the fix is to write the line correctly.

3An exception: the program was running, and stopped

runtime_error.py
print('this DOES appear')

marks = 10 / 0

print('this does not')
Output
this DOES appear
Traceback (most recent call last):
  File "runtime_error.py", line 3, in <module>
    marks = 10 / 0
            ~~~^~~
ZeroDivisionError: division by zero

Completely different. The first line ran and printed. The file is perfectly valid Python — dividing by a variable that happens to hold zero is a normal thing to write. Python only discovered the problem at the moment it tried to do the division.

That moment is the point. The program was alive, and something went wrong. It is alive right up until Python gives up and prints the red text — and being alive means you can be given a chance to respond. That chance is what the rest of this chapter is about.

Key Takeaway
An exception is an error that happens while the program is running. Python raises it, and if nobody deals with it, Python prints a traceback and stops the program. If somebody does deal with it, the program carries on.

4And the one you can never catch

logical_error.py
total = 80 + 90
average = total / 3        # should have been 2

print('average:', average)
Output
average: 56.666666666666664

No traceback, no red text, no exception. The program did exactly what you told it to and the answer is wrong. There is nothing here for try and except to notice, because as far as Python is concerned nothing went wrong at all.

Watch Out
Exception handling cannot save you from a logical error. It only ever deals with the middle kind — the ones Python itself objects to while running. A wrong formula is found by testing and reading, not by catching.

5Reading the red text

The traceback is not punishment. It is a report, and it has four useful parts. Read it from the bottom up:

What each line tells you
ZeroDivisionError

The TYPE of exception. This is the name you will write after except.

division by zero

The message — Python's one-line explanation of what it could not do.

File "runtime_error.py", line 3

Where it happened. Go there first.

marks = 10 / 0

The line itself, with a marker under the exact part that failed.

The last line of a traceback is the most useful line in it, and it is the one people skip. ZeroDivisionError: division by zero tells you both what went wrong and what to write in your except.

6Recap

Every exception is an error

But not every error is an exception. 'Exception' is the name for the run-time kind specifically.

A syntax error runs nothing

Python reads the whole file first. If it is not valid Python, not one line executes — so there is nothing to catch.

An exception interrupts a live program

The lines above it already ran. That is exactly why you get a chance to respond to it.

A logical error raises nothing

The program finishes and the answer is wrong. Python never objects, so exception handling cannot help.

Read the traceback bottom-up

Last line: the type and the message. Above it: the file, the line number, and the line itself.

✍️ Now write these yourself
  1. 1

    Put a print above a missing colon and confirm it never appears.

    Hint · Nothing runs. That is the whole difference.

  2. 2

    Put a print above a division by zero and confirm it does appear.

    Hint · The program was running, so everything before it happened.

  3. 3

    Cause three different exceptions and write down the last line of each traceback.

    Hint · Try int('abc'), a list index that is too big, and a name you never created.

  4. 4

    Write a program with a logical error and check that Python says nothing at all.

    Hint · Divide by the wrong number. It runs perfectly and the answer is wrong.

Quick Check

Why does the print above a missing colon never appear?

Quick Check

Which of the three kinds of error is an exception?

Quick Check

Which line of a traceback names the exception type?