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