liveBook · Manning

Try-catch statement

As explained in The Quick Python Book, Fourth Edition

A try-catch statement is a control-flow construct that executes code under exception handling and transfers control to a matching handler when an exception is raised.

In Python, a try statement runs code that might raise an exception. Matching except clauses handle particular exception types, allowing a recoverable error to produce a fallback instead of ending the program. section 14.2.3

Control flows through the clauses as follows:

  • Python runs the try body first. If it raises an exception, Python searches the except clauses in order and runs the first matching handler. `except ValueError as error` makes the exception available as `error`; `as error` is optional. section 14.2.3
  • An optional else clause runs when the try body raises no exception. An optional finally clause runs at the end whether or not an exception was raised. section 14.2.3 section 3.4.7
  • If no handler matches, the exception travels up the call chain. A handler can name a tuple of exception types; a final bare `except:` catches exceptions without specifying a type. section 14.2.3
def cell_value(string):
   try:
       return float(string)
   except ValueError:
       if string == "":
           return 0
       else:
           return None

This small conversion function catches only `ValueError` from `float`: a blank spreadsheet cell becomes `0`, while other nonnumeric input becomes `None`. section 14.2.9

A spreadsheet formula can likewise run under try and return `None` if it raises `TypeError`. Keep handlers tied to errors that can reasonably occur: unnecessary try-except blocks obscure the logic, while catching `Exception` only to raise a vague replacement can hide the original traceback. section 14.2.9 section 14.4.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains handler order, exception binding, propagation, else and finally, then applies them without detailing interpreter internals.
Examples
Demonstrates spreadsheet cell conversion and formula fallbacks, alongside file processing with a custom exception.
What it assumes
Assumes familiarity with Python functions and built-in operations while spelling out try and except behavior.
What you can do after
Practice/perform targeted exception handling for conversion and calculation errors without obscuring useful tracebacks.
How it connects
Connects exception classes, raising exceptions, call chains, and context managers to runtime error handling.

Also explained in

Compare how 10 books explain try-catch statement →

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.