Log and re-raise

EasyException Handling Programs · 11 of 20

Write a Python program that logs an error and then re-raises it to the caller.

Advertisement
Output
log: could not open missing.txt
caller handled: No such file or directory

Approach

  1. A bare raise inside except re-raises the same exception.

Solution

Python
def load(path):    try:        return open(path).read()    except FileNotFoundError:        print("log: could not open", path)        raise try:    load("missing.txt")except FileNotFoundError as e:    print("caller handled:", e.strerror)
Output
log: could not open missing.txt
caller handled: No such file or directory

Learn the concept

New to this topic? Read the lesson, then come back.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment