Exceptions and control flow

Since exceptions are a means of control flow, they can be clumsy to demonstrate at the REPL, so in this chapter we'll be using a Python module to contain our code. Let's start with a very simple module we can use for exploring these important concepts and behaviors. Place the this code in a module called exceptional.py:

"""A module for demonstrating exceptions."""

def convert(s):
"""Convert to an integer."""
x = int(s)
return x

Import the convert() function from this module into the Python REPL:

$ python3
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from exceptional import convert

and call our function with a string to see that it has the desired effect:

>>> convert("33")
33

If we call our function with an object that can't be converted to an integer, we get a traceback from the int() call:

>>> convert("hedgehog")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "./exceptional.py", line 7, in convert
x = int(s)
ValueError: invalid literal for int() with base 10: 'hedgehog'

What's happened here is that int() raised an exception because it couldn't sensibly perform the conversion. We didn't have a handler in place, so it was caught by the REPL and the stack trace was displayed. In other words, the exception went unhandled.

The ValueError referred to in the stack trace is the type of the exception object, and the error message "invalid literal for int() with base 10: 'hedgehog' is part of the payload of the exception object that has been retrieved and printed by the REPL.

Notice that the exception propagates across several levels in the call stack:

Call stack Effect
int() Exception raised here
convert() Exception conceptually passes through here
REPL Exception caught here
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset