Exceptions

try, except, else and finally.

When something goes wrong, Python raises an exception. If nobody catches it, the program stops and prints a traceback, a report of where the error happened. Read it from the bottom up. The last line names the type of error and the message, and the lines above show the chain of calls that led to it.

The types you will see most often:

  • ValueError: a value of a suitable type, but wrong: int("abc");
  • TypeError: the operation does not fit the type: "a" + 1;
  • KeyError: there is no such key in the dictionary;
  • IndexError: the index is outside the list;
  • ZeroDivisionError: division by zero.

An error can be caught with a try/except block:

text = "abc"
try:
    number = int(text)
except ValueError:
    number = 0
print(number)   # 0

Catch the specific type you expect. A bare except: or except Exception: pass swallows everything, including typos in names, and turns a clear error into puzzling behaviour.

The else block runs if there was no error, and finally runs always, even after return. In finally you close resources and write what must happen in any case. Several types can be caught in one block: except (ValueError, TypeError):. The error message is available through except ValueError as error: and then print(error).

Put into try only the line that can fail in the expected way. The smaller the block, the lower the risk of catching someone else's error by accident.

Practice

  1. Catching

    What does the program print?

    try:
        int("abc")
    except ValueError:
        print("bad")
    
  2. Which error

    Which exception does the expression [1, 2][5] raise?

    • IndexError
    • KeyError
    • ValueError
    • TypeError
  3. A safe number

    Write a function safe_int(text, default=0) that returns int(text), or default if the string is not a number.