Handling multiple exceptions

Each try block can have multiple corresponding except blocks which intercept exceptions of different types. Let's add a handler for TypeError too:

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
except TypeError:
print("Conversion failed!")
x = -1
return x

Now if we re-run the same test in a fresh REPL we find that TypeError is handled too:

>>> from exceptional import convert
>>> convert([1, 3, 19])
Conversion failed!
-1

We've got some code duplication between our two exception handlers with that duplicated print statement and assignment. We'll move the assignment in front of the try block, which doesn't change the behavior of the program:

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

Then we'll exploit the fact that both handlers do the same thing by collapsing them into one, using the ability of the except statement to accept a tuple of exception types:

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

Now we see that everything still works as designed:

>>> from exceptional import convert
>>> convert(29)
Conversion succeeded! x = 29
29
>>> convert("elephant")
Conversion failed!
-1
>>> convert([4, 5, 1])
Conversion failed!
-1
..................Content has been hidden....................

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