Python Practice › Exception Handling Programs › Program 20
Exception hierarchy order
Write a Python program showing why specific exceptions must be caught before general ones.
Output
True True specific handler: file not found
Approach
FileNotFoundErroris a subclass ofOSError, so it must come first.
Solution
print(issubclass(FileNotFoundError, OSError), issubclass(OSError, Exception))try: open("nope.txt")except FileNotFoundError: print("specific handler: file not found")except OSError: print("general handler: some OS error")Output
True True specific handler: file not found
Line by line
Line 1
Python checks except blocks top to bottom and uses the first that matches, so a general OSError first would hide the specific one.
Learn the concept
New to this topic? Read the lesson, then come back.