liveBook · Manning

Try-catch statement

As explained in Python How-To

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.

Need to convert a string that might not be a number? In Python, the construct often called try-catch is written `try...except`. Put the conversion in `try` and handle its expected exception in `except`. If conversion succeeds, Python skips the handler. If it fails, Python skips the rest of the `try` clause and runs the matching handler instead. section 12.3.1 section 2.2.2

Handle an invalid number

```python def cast_number(number_str): try: number = float(number_str) except ValueError: print(f"Couldn't cast {number_str!r} to a number") else: print(f"Casting {number_str!r} to {number}") cast_number("1.5") cast_number("2.3a") ``` Output: ```text Casting '1.5' to 1.5 Couldn't cast '2.3a' to a number ``` The `else` clause runs only when conversion succeeds. The invalid string raises `ValueError`, so its handler runs instead. section 2.2.2 section 12.4.1

Keep the handler specific and the control flow clear:

  • Keep `try` short: include only the operation that may raise the exception you intend to handle. section 12.3.1
  • Name the expected exception, such as `ValueError`, rather than using a bare `except`. During development, consult Python documentation or run the problematic operation to identify its exception. section 12.6 section 12.3.6
  • Use `except ValueError as ex` when the error detail would help explain a failure. A handler can also return early; without that return, later code might use a value the failed operation never assigned. section 12.3.4 section 12.4
  • Use `else` for work that should happen only after success. Use `finally` for cleanup that must run whether or not `try` raises an exception. section 12.4.1 section 12.6

Handle failures where they matter to the task. A missing item in a sequence can be handled when `index()` raises `ValueError`, rather than checking membership before searching. In a web app, an update can also need exception handling if a user has deleted the item being edited. The aim is not to hide every error, but to respond to expected failures without abruptly stopping the application. section 4.3.5 section 14.4.6 section 12.3.5

How Python How-To covers it

How deep it goes
Works through exception-path control flow, specific handlers, captured error details, and optional else and finally clauses.
Examples
Uses valid and invalid numeric strings, a failed task-string conversion, and an update to a deleted database item.
What it assumes
Assumes familiarity with Python functions and conversions while explaining exception-handling control flow from its basic clauses.
What you can do after
Build it from scratch by placing a failure-prone operation in try and handling its expected exception explicitly.
How it connects
Connects exception handling with ValueError, numeric conversion, EAFP, sequence indexing, and cleanup.

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 Python How-To. The section links point to the parts of the book it draws on.