The try-except block can be extended with two more clauses, and an exception can also be raised deliberately. The exceptions themselves are arranged as a family of classes.

try-except-else-finally

The else clause runs only when the try block finishes without any exception. It is the place for code that depends on the success of the try block. The finally clause always runs, whether or not an exception occurred and even if the program is about to stop because of an unhandled one. It is used for clean-up such as closing a file. The order must be try, except, else, finally.

Definition: finally clause. A block attached to try that is always executed, whether or not an exception occurred, and is used for clean-up actions.

The raise Statement

The raise statement creates an exception on purpose. For example, raise ValueError("age cannot be negative") stops the current code with that error, unless it is caught. It is used when a function finds that its input is not acceptable. A bare raise inside an except block raises the same exception again.

Hierarchy of Exceptions

Exceptions are classes arranged in a tree. At the top is BaseException, and below it is Exception, from which almost all ordinary errors descend. ArithmeticError is the parent of ZeroDivisionError and OverflowError, and LookupError is the parent of IndexError and KeyError. Because an except block catches the named class and all its subclasses, except ArithmeticError would also catch ZeroDivisionError. More specific blocks must be listed before more general ones.

User Defined Exceptions

A programmer can add an exception by defining a class that inherits from Exception, as in class NegativeError(Exception): pass. It can then be raised and caught like a built-in one, which makes error messages meaningful for the application.

Table 4.2: Clauses of the try statement

Clause Runs when Typical use
try Always first Risky code
except An exception occurs Recovery
else No exception occurs Code that depends on success
finally Always Clean-up

Example 4.2: Duplicates in a list and clean-up

Problem: Write a function that raises an exception if a list of integers has a duplicate, and test it with try, except, else and finally.

Solution:

  1. Compare len(L) with len(set(L)). If different, raise ValueError.
  2. Call the function in a try block with matching except, else and finally parts.

Result: For [1, 2, 3, 2] the except block runs, for [1, 2, 3] the else block runs, and finally runs in both cases.

def check(L):
    if len(L) != len(set(L)):
        raise ValueError("duplicate found")
    return True

class NegativeError(Exception):
    pass

for data in ([1, 2, 3, 2], [1, 2, 3]):
    try:
        check(data)
    except ValueError as e:
        print("Error:", e)
    else:
        print("No duplicates")
    finally:
        print("checked", data)
try:
    raise NegativeError("value below zero")
except NegativeError as e:
    print(e)
print(ZeroDivisionError.__mro__[1].__name__)

Output

Error: duplicate found
checked [1, 2, 3, 2]
No duplicates
checked [1, 2, 3]
value below zero
ArithmeticError

Common mistakes

  • Putting the else clause before except. The order is try, except, else, finally.
  • Expecting finally to run only after an error. It always runs.
  • Listing a general exception before a specific one so that the specific block never runs.

Key takeaways

  • else runs only when no exception occurred.
  • finally always runs and is used for clean-up.
  • raise creates an exception on purpose.
  • A user defined exception is a class that inherits from Exception.

Practice questions

  1. When does the else clause of try run?
  2. Which clause always runs?
  3. How is a user defined exception created?

Answers to the practice questions

  1. When the try block finishes without an exception.
  2. finally.
  3. By defining a class that inherits from Exception.

Sources

  • Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit IV