- 5.1 Function Definitions
- 5.2 Default Arguments
- 5.3 Variadic Arguments
- 5.4 Keyword Arguments
- 5.5 Variadic Keyword Arguments
- 5.6 Functions Accepting All Inputs
- 5.7 Positional-Only Arguments
- 5.8 Names, Documentation Strings, and Type Hints
- 5.9 Function Application and Parameter Passing
- 5.10 Return Values
- 5.11 Error Handling
- 5.12 Scoping Rules
- 5.13 Recursion
- 5.14 The lambda Expression
- 5.15 Higher-Order Functions
- 5.16 Argument Passing in Callback Functions
- 5.17 Returning Results from Callbacks
- 5.18 Decorators
- 5.19 Map, Filter, and Reduce
- 5.20 Function Introspection, Attributes, and Signatures
- 5.21 Environment Inspection
- 5.22 Dynamic Code Execution and Creation
- 5.23 Asynchronous Functions and await
- 5.24 Final Words: Thoughts on Functions and Composition
5.11 Error Handling
One problem with the parse_value() function in the previous section is error handling. What course of action should be taken if the input text is malformed and no correct result can be returned?
One approach is to treat the result as optional—that is, the function either works by returning an answer or returns None which is commonly used to indicate a missing value. For example, the function could be modified like this:
def parse_value(text): parts = text.split('=', 1) if len(parts) == 2: return ParseResult(parts[0].strip(), parts[1].strip()) else: return None
With this design, the burden of checking for the optional result is placed on the caller:
result = parse_value(text) if result: name, value = result
Or, in Python 3.8+, more compactly as follows:
if result := parse_value(text): name, value = result
Instead of returning None, you could treat malformed text as an error by raising an exception. For example:
def parse_value(text): parts = text.split('=', 1) if len(parts) == 2: return ParseResult(parts[0].strip(), parts[1].strip()) else: raise ValueError('Bad value')
In this case, the caller is given the option of handling bad values with try-except. For example:
try: name, value = parse_value(text) ... except ValueError: ...
The choice of whether or not to use an exception is not always clear-cut. As a general rule, exceptions are the more common way to handle an abnormal result. However, exceptions are also expensive if they frequently occur. If you’re writing code where performance matters, returning None, False, -1, or some other special value to indicate failure might be better.