Home > Articles

This chapter is from the book

This chapter is from the book

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.