MCS-201 · Unit 14

Exception Handling in Python Programming

Section 2 of 5

Block 4 · Unit 14Exception Handling in Python Programming12 min · Section 2 of 5

14.2Catching Exceptions with try and except

Covers IGNOU MCS-201 §14.3

Handling an exception means placing the risky code in a try block and the recovery code in an except block. The program then continues normally instead of stopping.

The try statement

Syntax
try:
    code that might raise an exception
except ExceptionType:
    code that runs if that exception occurs

How it runs:

  1. The try block runs.
  2. If no exception occurs, the except blocks are skipped.
  3. If an exception occurs, the rest of the try block is skipped, and Python looks for the first except clause whose type matches. Its block runs, and the program continues after the whole try statement.
  4. If no except clause matches, the exception travels outward, and if nobody handles it, the default handler stops the program.

except ExceptionType as e: gives the exception object a name, so you can print its message with print(e).

Several except clauses

FormCatches
except ZeroDivisionError:Only that type (and its subclasses)
except (ValueError, TypeError) as e:Any of the listed types
except Exception as e:Almost all errors (not KeyboardInterrupt or SystemExit)
except: (bare)Absolutely everything, including Ctrl+C; avoid

Clauses are checked from top to bottom and only the first match runs, so put specific types before general ones. A bare except: must be the last clause, otherwise Python reports a SyntaxError.

The exception hierarchy

Every exception is an object of a class, and the classes form a hierarchy. An except clause catches its class and all its subclasses.

Part of the built-in exception hierarchy
BaseException
 ├── SystemExit, KeyboardInterrupt, GeneratorExit
 └── Exception
      ├── ArithmeticError ── ZeroDivisionError, OverflowError, FloatingPointError
      ├── LookupError ────── IndexError, KeyError
      ├── OSError ────────── FileNotFoundError, PermissionError, TimeoutError
      ├── NameError, TypeError, ValueError, AttributeError, EOFError, ...

So except LookupError: catches both IndexError and KeyError, and except ArithmeticError: catches ZeroDivisionError.

Key takeaways

  • try holds risky code; except holds the handler.
  • Use specific exception types; group them with a tuple.
  • as err gives the exception object; print(err) shows its message.
  • An except for a class also catches its subclasses; order clauses from specific to general.

Practice questions

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

Question 1 · multiple choice

What happens to the remaining statements in a try block after an exception occurs?

Show answer

Answer: B. They are skipped

Control jumps from the failing line straight to the matching except clause.

Question 2 · multiple choice

Which clause catches both IndexError and KeyError?

Show answer

Answer: C. except LookupError:

IndexError and KeyError are both subclasses of LookupError.

Question 3 · multiple choice

What does this program print?

Python · quiz_try.py
try:
    n = int("12")
    print(n / 0)
    print("done")
except ValueError:
    print("bad value")
except ZeroDivisionError:
    print("zero")
print("end")
Show answer

Answer: C. zero, end

“12” converts fine; dividing by zero jumps to the ZeroDivisionError handler, skipping “done”, then execution continues with “end”.

Question 4 · multiple choice

Which clause order is correct?

Show answer

Answer: B. except ValueError: then except Exception:

The first matching clause wins, so a general clause placed first would hide the specific one; a bare except: must be last.

Question 5 · multiple choice

What does this program print?

Python · quiz_as.py
try:
    [1, 2, 3].index(7)
except ValueError as e:
    print(type(e).__name__)
Show answer

Answer: D. ValueError

list.index raises ValueError when the item is absent; type(e).__name__ gives the class name.

Question 6 · short answer

Write a function read_age(text) that returns the age as an integer, or prints a message and returns None if the text is not a whole number.

Show worked answer

def read_age(text): with try: return int(text) and except ValueError: print("Age must be a whole number"); return None. For read_age("31") it returns 31; for read_age("thirty") it prints the message and returns None. Only ValueError is caught, because that is the error int() raises for unconvertible text; other mistakes would still be reported.

↑ ↓ move↵ openTab switch type