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.
| Kind | When it is found | Example | What happens |
|---|---|---|---|
| Syntax error | While Python parses the program, before it runs | if x > 5 without a colon | Nothing runs; Python reports SyntaxError |
| Exception (runtime error) | While the program runs | 10 / 0 | Python raises ZeroDivisionError |
| Logical error | Only by testing the results | Area worked out as 2 * (l + w) | Program runs but prints a wrong answer (Area: 26) |
| Part of the error line | For this program |
|---|---|
| Exception name (the class of the error) | IndexError |
| Message (details) | list index out of range |
| Output printed before the error | Start |
| Statement never reached | print("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.
| Statement | Error line from Python | Cause |
|---|---|---|
int("7k") | ValueError: invalid literal for int() with base 10: '7k' | right type, unsuitable value |
"Rs " + 50 | TypeError: can only concatenate str (not "int") to str | operation on an unsuitable type |
print(totl) | NameError: name 'totl' is not defined | name never assigned |
[3, 9][2] | IndexError: list index out of range | sequence index out of range |
{"tea": 10}["milk"] | KeyError: 'milk' | dictionary key missing |
45 // 0 | ZeroDivisionError: integer division or modulo by zero | divisor is zero |
| Statement | Error line from Python | Cause |
|---|---|---|
open("notes_old.txt") | FileNotFoundError: [Errno 2] No such file or directory: 'notes_old.txt' | file not found (an OSError, also called IOError) |
import mathz | ModuleNotFoundError: No module named 'mathz' | module not found (an ImportError) |
import math; math.exp(1000) | OverflowError: math range error | number too large to store |
x = input() | EOFError: EOF when reading a line | input ended before a line was read |
| Line | Statement | Runs? | Result |
|---|---|---|---|
| 1 | stock = {...} | Yes | dictionary created |
| 2 | need = "oil" | Yes | name assigned |
| 3 | print("Checking", need) | Yes | prints Checking oil |
| 4 | qty = stock[need] | Fails | KeyError: 'oil' |
| 5 | print("Quantity:", qty) | No | never 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
| raise | assert | |
|---|---|---|
| Form | raise ValueError("msg") | assert condition, "msg" |
| When it throws | Every time it executes | Only if the condition is False |
| Exception | Any one you name | Always AssertionError |
| Typical use | Reject bad data in a finished program | Check assumptions while developing |
| Typed by the clerk | Output |
|---|---|
2500 | Recorded 2500 |
-300 | Not recorded: fee cannot be negative |
free | Not 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 Exceptionlast. 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.
| raw | Exception | Handler that runs | Printed |
|---|---|---|---|
"4" | none | none (try completes) | 25 |
"0" | ZeroDivisionError | except ZeroDivisionError | cannot share among zero |
"four" | ValueError | except ValueError | not a number |
| Form | Meaning |
|---|---|
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) |
| Clause order | Which handler runs for "Pune"[9]? |
|---|---|
| IndexError first, Exception last | index handler |
| Exception first, IndexError last | general 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
| What happened in try | except | else | finally |
|---|---|---|---|
| No exception | skipped | runs | runs |
| Exception, handled | matching one runs | skipped | runs |
| Exception, no matching handler | none runs | skipped | runs, then the program stops |
| v | Blocks executed | Lines printed |
|---|---|---|
| "5" | try → else → finally | R 6 / F 5 |
| "x" | try (int fails) → except ValueError → finally | V x / F x |
| "0" | try (division fails) → except ZeroDivisionError → finally | Z 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.
| Typed | What the program does |
|---|---|
| two | Invalid: invalid literal for int() with base 10: 'two' |
| 9 | Invalid: choose 1 to 6 |
| 3 | Booking 3 tickets |
| Do | Avoid |
|---|---|
| Keep the try block small: only the risky statements | Putting the whole program in one try |
| Catch the specific exceptions you expect | A bare except: that hides every bug |
| Give a helpful message, or ask again | Silently ignoring errors with pass |
Put clean-up in finally | Repeating clean-up in every handler |
Write except Exception last, if at all | A 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" + 5a 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 Exceptionbefore specific clauses. - Misspelling exception names (
ValueEror) or forgetting the colon aftertryandexcept.
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.