MCS-201 · Unit 14

Exception Handling in Python Programming

Section 1 of 5

Block 4 · Unit 14Exception Handling in Python Programming9 min · Section 1 of 5

14.1Errors and the Default Exception Handler

Covers IGNOU MCS-201 §14.0, 14.2

Before handling errors, you need to know what kinds there are and what Python does on its own when one occurs.

Two kinds of errors

Syntax errorException (run-time error)
When detectedWhile Python compiles the file, before any line runsWhile the program runs
CauseCode that breaks the language’s grammar: missing colon, unmatched bracketValid code meets an impossible situation: division by zero, missing file, wrong type
Exampleprint("Hi", (3+4], lst = [4;5;6]3 / 0, int("22.5"), [1, 2][5]
Can the program catch it?Not in the same file (the file never starts)Yes, with try and except

A third kind, the logical error, produces wrong results without any message (for example using + where * was intended); only testing finds these.

Common built-in exceptions

ExceptionRaised whenExample
ZeroDivisionErrorDividing by zero3 / 0
IndexErrorA sequence index is out of range[2, 3, 4][5]
KeyErrorA dictionary key is missing{"a": 1}["b"]
NameErrorA name is not definedx + 3 with no x
TypeErrorAn operation gets an unsuitable type'2' * '3'
ValueErrorThe type is right but the value is not acceptableint('22.5')
AttributeErrorAn object has no such attribute(5).append(1)
FileNotFoundErrorA file to be opened for reading does not existopen("missing.txt")
OverflowErrorA float result is too large to represent2.0 ** 10000
ImportError, ModuleNotFoundErrorAn import failsimport nosuchmodule
KeyboardInterruptThe user presses Ctrl+Cwhile a long loop runs

The default exception handler

If an exception is not handled, Python’s default exception handler takes over: it prints a traceback (the chain of calls that led to the error, the line number, the exception type and its message) and ends the program. Any statements after the failing one do not run; this is called abnormal termination.

Key takeaways

  • Syntax errors are found before running; exceptions happen during running.
  • Learn the common exceptions: ZeroDivisionError, IndexError, KeyError, NameError, TypeError, ValueError, FileNotFoundError.
  • Unhandled exceptions print a traceback and end the program.
  • Read a traceback from the bottom up.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

Which error is raised by int("abc")?

Show answer

Answer: B. ValueError

int() accepts strings, so the type is fine, but this string’s value cannot be converted.

Question 2 · multiple choice

Which error is raised by {"name": "Asha"}["age"]?

Show answer

Answer: C. KeyError

Looking up a missing dictionary key raises KeyError; IndexError is for sequence positions.

Question 3 · multiple choice

What does this program print before it stops?

Python · quiz_stop.py
print("A")
x = [1, 2, 3]
print(x[3])
print("B")
Show answer

Answer: A. A, then a traceback ending in IndexError

“A” is printed, x[3] raises IndexError (the last index is 2), and “B” is never reached.

Question 4 · multiple choice

When is a SyntaxError reported?

Show answer

Answer: B. Before the program starts running

Python compiles the whole file first, so grammar errors are found before any line runs.

Question 5 · multiple choice

What does '2' * '3' raise?

Show answer

Answer: D. TypeError: can't multiply sequence by non-int of type 'str'

A string can be multiplied by an integer (repetition), but not by another string.

Question 6 · short answer

Explain the difference between a syntax error, an exception and a logical error, with one example each.

Show worked answer

A syntax error breaks Python’s grammar and is detected before the program runs, for example if x > 3 without the colon. An exception is a run-time error in grammatically correct code, raised when an operation cannot be performed, for example 10 / 0 raising ZeroDivisionError; it can be caught with try/except. A logical error produces no message but gives wrong results, for example computing an average as total / 2 when there are three values; it is found only by testing.

↑ ↓ move↵ openTab switch type