Bird
Raised Fist0

Consider this code:

hard🚀 Application Q9 of Q15
Python - Exception Handling Fundamentals
Consider this code:
def read_file(filename):
    try:
        with open(filename) as f:
            return f.read()
    except Exception as e:
        return str(e)

print(read_file('missing.txt'))

What is the purpose of catching Exception as e here?
ATo ignore all errors silently
BTo catch any error and return its message instead of crashing
CTo only catch file not found errors
DTo raise the error again after catching
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the try-except block

    The code tries to open and read a file; if any error occurs, it catches it as 'e'.
  2. Step 2: Understand the except block's action

    Instead of crashing, it returns the error message as a string, allowing graceful handling.
  3. Final Answer:

    To catch any error and return its message instead of crashing -> Option B
  4. Quick Check:

    Catch all exceptions to handle errors gracefully [OK]
Quick Trick: Catch Exception to handle all errors gracefully [OK]
Common Mistakes:
MISTAKES
  • Thinking it ignores errors silently
  • Assuming it only catches file not found errors
  • Believing it re-raises the error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes