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









