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









