Handling exceptions

Let's make our convert() function more robust by handling the ValueError using a tryexcept construct. Both the try and except keywords introduce new blocks. The try block contains code that could raise an exception and the except block contains the code which performs error handling in the event that an exception is raised. Modify the convert() function to look like this:

def convert(s):
"""Convert a string to an integer."""
try:
x = int(s)
except ValueError:
x = -1
return x

We have decided that if a non-integer string is supplied, we'll return minus one. To reinforce your understanding of the control-flow here we'll also add a couple of print statements:

def convert(s):
"""Convert a string to an integer."""
try:
x = int(s)
print("Conversion succeeded! x =", x)
except ValueError:
print("Conversion failed!")
x = -1
return x

Let's test this interactively after restarting the REPL:

>>> from exceptional import convert
>>> convert("34")
Conversion succeeded! x = 34
34
>>> convert("giraffe")
Conversion failed!
-1

Note how the print() in the try block after the point at which the exception was raised was not executed when we passed in "giraffe" as the function argument. Instead, execution was transferred directly to the first statement of the except block.

The int() constructor only accepts numbers or strings, so let's see what happens if we feed an object of another type into it, say a list:

>>> convert([4, 6, 5])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "./exceptional.py", line 8, in convert
x = int(s)
TypeError: int() argument must be a string or a number, not 'list'

This time our handler didn't intercept the exception. If we look closely at the trace, we can see that this time we received a TypeError – a different type of exception.

..................Content has been hidden....................

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