StudyToCert

All certifications / PCEP / Lessons

PCEP – Certified Entry-Level Python Programmer PCEP-30-02 · Domain 4: Functions and exceptions

Ordering except branches from specific to general

▶ Watch the overview video

Last reviewed September 30, 2026 · Leer en español

When an exception is raised inside a try block, Python checks the except clauses from top to bottom and runs the first one that matches. A clause matches if the exception is an instance of the named class or of any of its subclasses. Once a clause has matched, no later clauses are considered, even if a later one names the exact class that was raised. This first-match rule is why the order of except branches matters, and why PCEP (Certified Entry-Level Python Programmer) questions so often show several branches and ask which one prints. Consider what happens if a general class comes first. except Exception: matches almost every error, and except LookupError: matches both IndexError and KeyError. If you put one of these above a more specific clause, the specific clause can never run: it is unreachable, or dead code. Python does not report an error for this; the code runs normally, and the specific branch simply never gets its turn.

Free account

Keep reading for free

Create a free StudyToCert account to read the rest of this lesson: 7 more sections, 6 key terms, a real-world example, an exam tip and self-check questions. Every lesson, lab and practice test is free with an account.

Sign up free Log in

Study PCEP for free
A week-by-week plan with every lesson, quizzes, checkpoint tests, a practice exam and hands-on labs.
Open the PCEP study plan