From CS 61A Wiki
Revision as of 15:47, 24 July 2014 by Axis (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Jump to: navigation, search

An exception is an object that represents an error.[1] Exceptions are raised either automatically by Python or explicitly by the programmer.

This is a full list of exceptions: https://docs.python.org/3/library/exceptions.html#bltin-exceptions.


There are two different types of exceptions: ones that happen when the program is being parsed by Python (SyntaxError, IndentationError), and ones that happen when the program is running (runtime exceptions).

Raising an exception

Use the raise statement. Example:

>>> while True:
...     num = int(input("Enter a number between 1 and 10:\n"))
...     if not 1 <= num <= 10:
...         raise ValueError("Number out of range")
Enter a number between 1 and 10:
Enter a number between 1 and 10:
Traceback (most recent call last):
ValueError: Number out of range

Handling an exception

Runtime exceptions can be caught. We use the try-except construct to handle an exception. If an error is encountered in the try block, execution stops and is transferred to the except block.


>>> try:
...     print(1/0)
... except ZeroDivisionError:
...     print("Can't divide by zero!")
Can't divide by zero!

There can be multiple except clauses for different types of exceptions. An except clause can also not have an exception specified, in which case it would handle all runtime exceptions. Example:

>>> try:
...     lst = None
...     lst.append(2)
... except:
...     print("Something bad happened!")
Something bad happened!


  1. https://docs.google.com/presentation/d/1j_a3kWQwnqyFRo5ud1iJUzVKPK37JkQna9_m9h2u7O0/edit#slide=id.g38ed26997_126