Python Practice › Exception Handling Programs › Program 11
Log and re-raise
Write a Python program that logs an error and then re-raises it to the caller.
Output
log: could not open missing.txt caller handled: No such file or directory
Approach
- A bare
raiseinsideexceptre-raises the same exception.
Solution
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.