Exception hierarchy order

EasyException Handling Programs · 20 of 20

Write a Python program showing why specific exceptions must be caught before general ones.

Advertisement
Output
True True
specific handler: file not found

Approach

  1. FileNotFoundError is a subclass of OSError, so it must come first.

Solution

Python
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.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment