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...