June 2017
Beginner
352 pages
8h 39m
English
Let's make our convert() function more robust by handling the ValueError using a try … except 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 ...
Read now
Unlock full access