Bird
0
0

Find the error in this code snippet:

medium📝 Debug Q14 of 15
Python - Custom Exceptions
Find the error in this code snippet:
try:
    open('file.txt')
except IOError:
    print('File error')
except FileNotFoundError:
    print('File not found')
Aopen() needs a mode argument
BIOError should be replaced with Exception
CNo error, code is correct
DFileNotFoundError should come before IOError
Step-by-Step Solution
Solution:
  1. Step 1: Understand exception hierarchy between IOError and FileNotFoundError

    FileNotFoundError is a subclass of IOError.
  2. Step 2: Check order of except blocks

    The more specific exception (FileNotFoundError) must come before the more general (IOError) to avoid unreachable code.
  3. Final Answer:

    FileNotFoundError should come before IOError -> Option D
  4. Quick Check:

    Specific exceptions must precede general ones [OK]
Quick Trick: Place child exceptions before parent exceptions in except blocks [OK]
Common Mistakes:
  • Putting general exceptions before specific ones
  • Assuming IOError and FileNotFoundError are unrelated
  • Thinking open() requires mode argument always

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes