Skip to content
Skip to page content
soylai.com

Exception Handling — Notes

6 sections 5 min readBeta

1. Errors and exceptions

Syntax errors break Python's grammar (missing colon, unmatched bracket, = for == in a condition). Python finds them while parsing, before running, so no statement runs and they cannot be handled in the same program.

Exceptions (runtime errors) occur while a valid program runs, e.g. 10 / 0. Python creates an exception object and looks for a handler; with none, the program stops and prints a traceback whose last line is ExceptionName: message.

Logical errors give wrong results with no message; only testing reveals them.

Exception handling deals with the middle row.
KindWhen it is foundExampleWhat happens
Syntax errorWhile Python parses the program, before it runsif x > 5 without a colonNothing runs; Python reports SyntaxError
Exception (runtime error)While the program runs10 / 0Python raises ZeroDivisionError
Logical errorOnly by testing the resultsArea worked out as 2 * (l + w)Program runs but prints a wrong answer (Area: 26)
Syntax errors stop the program before it starts.
The last line of a traceback names the exception and gives a message.
Part of the error lineFor this program
Exception name (the class of the error)IndexError
Message (details)list index out of range
Output printed before the errorStart
Statement never reachedprint("End")

Key terms

Syntax error

An error in the grammar of the program, found while parsing; no statement runs.

Exception

An error that occurs while a program is running; it can be handled.

Traceback

The report Python prints for an unhandled exception, ending with the exception name and message.

2. Built-in exceptions

Each built-in exception is a class named after the problem:

  • ValueError — right type, unsuitable value: int("7k")
  • TypeError — unsuitable type for an operation: "Rs " + 50
  • NameError — name not defined
  • IndexError — sequence index out of range
  • KeyError — dictionary key missing
  • ZeroDivisionError — divisor zero in /, // or %
  • FileNotFoundError (an OSError, also called IOError) — file missing
  • ImportError (and ModuleNotFoundError) — import fails
  • EOFError — input() reaches end of input
  • OverflowError — result too large
  • SyntaxError — grammar error

The error lines in the tables were produced by Python 3.12; older versions word some messages slightly differently, but the exception names are the same.

Table of six common built-in exceptions, each produced by running the statement in Python: ValueError, TypeError, NameError, IndexError, KeyError and ZeroDivisionError, with their causes
StatementError line from PythonCause
int("7k")ValueError: invalid literal for int() with base 10: '7k'right type, unsuitable value
"Rs " + 50TypeError: can only concatenate str (not "int") to stroperation on an unsuitable type
print(totl)NameError: name 'totl' is not definedname never assigned
[3, 9][2]IndexError: list index out of rangesequence index out of range
{"tea": 10}["milk"]KeyError: 'milk'dictionary key missing
45 // 0ZeroDivisionError: integer division or modulo by zerodivisor is zero
IOError is another name for OSError in Python 3.
StatementError line from PythonCause
open("notes_old.txt")FileNotFoundError: [Errno 2] No such file or directory: 'notes_old.txt'file not found (an OSError, also called IOError)
import mathzModuleNotFoundError: No module named 'mathz'module not found (an ImportError)
import math; math.exp(1000)OverflowError: math range errornumber too large to store
x = input()EOFError: EOF when reading a lineinput ended before a line was read
Produced by running the program in Python.
LineStatementRuns?Result
1stock = {...}Yesdictionary created
2need = "oil"Yesname assigned
3print("Checking", need)Yesprints Checking oil
4qty = stock[need]FailsKeyError: 'oil'
5print("Quantity:", qty)Nonever reached

Key terms

Built-in exception

An exception class provided by Python, such as ValueError or KeyError.

IOError

Another name for OSError in Python 3; raised for input-output failures such as a missing file.

3. Raising exceptions: raise and assert

raise throws a named exception deliberately: raise ValueError("fee cannot be negative"). The rest of the block is skipped, and a matching handler (or the end of the program) follows.

assert checks a condition: assert cond, "message" raises AssertionError with the message only when the condition is False; it is mainly used to check assumptions during development.

limit = 3
try:
    assert limit >= 5, "limit too small"
except AssertionError as e:
    print("Check failed:", e)

Output: Check failed: limit too small

Comparison table of raise and assert: raise throws the named exception every time it runs and is used to reject bad data; assert throws AssertionError only when its condition is False and is used to check assumptions
raiseassert
Formraise ValueError("msg")assert condition, "msg"
When it throwsEvery time it executesOnly if the condition is False
ExceptionAny one you nameAlways AssertionError
Typical useReject bad data in a finished programCheck assumptions while developing
raise throws an exception on purpose.
Each run was executed in Python with the typed input.
Typed by the clerkOutput
2500Recorded 2500
-300Not recorded: fee cannot be negative
freeNot recorded: invalid literal for int() with base 10: 'free'

Key terms

raise

A statement that throws a named exception, usually with a message.

assert

A statement that raises AssertionError if its condition is False.

4. try and except

Risky statements go in try; handlers go in except clauses.

  • The try block stops at the first failing statement; the rest of it is skipped.
  • Python compares the exception with the except clauses top to bottom and runs the first match; specific handlers first, except Exception last.
  • except (ValueError, TypeError): handles either; except ValueError as e: keeps the object, print(e) shows the message.
  • A bare except: catches everything and hides bugs.
  • After the handler, execution continues after the whole try statement.
finally is on every path.
Each row comes from running the loop in Python.
rawExceptionHandler that runsPrinted
"4"nonenone (try completes)25
"0"ZeroDivisionErrorexcept ZeroDivisionErrorcannot share among zero
"four"ValueErrorexcept ValueErrornot a number
Table of except clause forms: one named exception, a tuple of exceptions, the as form that keeps the exception object, the general Exception class written last, and the bare except which should be avoided
FormMeaning
except ValueError:handles one exception
except (ValueError, TypeError):one handler for either exception (a tuple)
except ValueError as e:e holds the exception object; print(e) shows its message
except Exception:almost any runtime error (write it last)
except:every exception (avoid: hides bugs)
Python runs the first matching clause, top to bottom.
Clause orderWhich handler runs for "Pune"[9]?
IndexError first, Exception lastindex handler
Exception first, IndexError lastgeneral handler

Key terms

Exception handler

The block under an except clause that deals with a particular exception.

Catching an exception

Finding a matching except clause and running its handler.

5. else and finally

Order: try, except …, else, finally.

  • else runs only if the try block raised no exception: use it for work that needs the risky step to succeed.
  • finally runs in every case (success, handled error, unhandled error, break): use it for clean-up such as closing files.
try:
    qty = int("3")
except ValueError:
    print("bad")
else:
    print("qty", qty)
finally:
    print("done")

Output:

qty 3
done
Table of which clauses run: with no exception, else and finally run; with a handled exception, the matching except and finally run; with an unhandled exception only finally runs and then the program stops
What happened in tryexceptelsefinally
No exceptionskippedrunsruns
Exception, handledmatching one runsskippedruns
Exception, no matching handlernone runsskippedruns, then the program stops
Typical uses: closing files and connections, saving logs.
Lines printed are from running the loop in Python (separated by /).
vBlocks executedLines printed
"5"try → else → finallyR 6 / F 5
"x"try (int fails) → except ValueError → finallyV x / F x
"0"try (division fails) → except ZeroDivisionError → finallyZ 0 / F 0

Key terms

else clause

Runs after the try block only when no exception was raised.

finally clause

Always runs at the end of the try statement; used for clean-up.

6. Recovering and good practice

Put the input step inside a loop with try-except, and break when the input is valid; use raise inside try for values outside the allowed range so that one handler deals with all invalid entries. Keep try blocks small, catch specific exceptions, show helpful messages, and avoid a bare except or a silent pass.

Run in Python with the inputs two, 9 and 3.
TypedWhat the program does
twoInvalid: invalid literal for int() with base 10: 'two'
9Invalid: choose 1 to 6
3Booking 3 tickets
Table of good practice in exception handling: keep try blocks small, catch specific exceptions, give helpful messages, put clean-up in finally and write any general handler last; avoid a bare except, silent pass and a general handler first
DoAvoid
Keep the try block small: only the risky statementsPutting the whole program in one try
Catch the specific exceptions you expectA bare except: that hides every bug
Give a helpful message, or ask againSilently ignoring errors with pass
Put clean-up in finallyRepeating clean-up in every handler
Write except Exception last, if at allA general handler before specific ones

Key terms

Input validation loop

A loop that keeps asking for input until a valid value is entered, using try-except and break.

Exam tips

Common mistakes

  • Calling int("4.5") a TypeError (it is a ValueError) or "5" + 5 a ValueError (it is a TypeError).
  • Writing output for a syntax-error program: there is none.
  • Forgetting that finally prints in every pass, even after break.
  • Thinking execution returns to the failed line after a handler.
  • Putting except Exception before specific clauses.
  • Misspelling exception names (ValueEror) or forgetting the colon after try and except.

How marks are usually awarded

  • Output questions: each correct line, in the right order.
  • Error-finding: the error named and corrected.
  • Programs: try around the risky step, correct handlers, and output shown for the inputs given.
  • Theory: one point per mark, with a short example where it helps.