liveBook · Manning

Except block

As explained in The Quick Python Book, Fourth Edition

An except clause is a branch of a Python try statement that handles exceptions matching a specified exception type.

An except block is the branch of a Python try statement that handles a matching exception instead of allowing it to terminate the program. Python checks except clauses in order and runs the first compatible one. section 14.2.3

Use these forms to control what the handler catches:

  • Write `except ExceptionType:` to catch one exception type without binding the exception. section 14.2.3
  • Write `except ExceptionType as error:` to bind the thrown exception for inspection or reporting. section 14.2.3
  • Use a tuple such as `except (TypeA, TypeB):` when one block should handle several exception types. section 14.2.3
  • Place narrower exception types before broader ones: because `IndexError` inherits from `LookupError`, a preceding `except LookupError` makes a later `except IndexError` unreachable for that error. section 14.2.7
  • Use a bare `except:` only as a final catch-all; otherwise, an unmatched exception continues up the call chain. section 14.2.3

Handling file-processing cases

A file-processing loop can catch `IOError` when opening a file and a custom `EmptyFileError` when the file contains no text. The matching except block reports the problem, while `else` handles successful reads and `finally` runs for every file. section 3.4.7

try:
   body
except exception_type1 as var1:
   exception_code1
except exception_type2 as var2:
   exception_code2
except (exception_type3, exception_type4  as var3:
   exception_code3
   .
except:
   default_exception_code
else:
   else_body
finally:
   finally_body

Use the complete syntax listing to compare typed handlers, tuple handlers, a default handler, and the optional else and finally clauses. section 14.2.3

try:
   body
except LookupError as error:
   exception code
except IndexError as error:
   exception code

Use the ordering example to see how inheritance determines which except block handles an exception. section 14.2.7

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains syntax, binding, tuples, propagation, and inheritance-based ordering, while deferring broader exception design details.
Examples
Demonstrates file reading with IOError, a custom EmptyFileError, ordered handlers, and completion reporting.
What you can do after
Apply Python except clauses to classify, report, and handle selected runtime errors.
How it connects
Connects try statements with exception hierarchy, custom exceptions, else clauses, finally clauses, and context managers.

Also explained in

Compare how 2 books explain except block →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.