Exception objects

Sometimes, we'd like to get hold of the exception object – in this case an object of type ValueError or TypeError - and interrogate it for more details of what went wrong. We can get a named reference to the exception object by tacking an as clause onto the end of the except statement with a variable name that will be bound to the exception object:

def convert(s):
"""Convert a string to an integer."""
try:
return int(s)
except (ValueError, TypeError) as e:
return -1

We'll modify our function to print a message with exception details to the stderr stream before returning. To print to stderr we need to get a reference to the stream from the sys module, so at the top of our module we'll need to import sys. We can then pass sys.stderr as a keyword argument called file to print():

import sys

def convert(s):
"""Convert a string to an integer."""
try:
return int(s)
except (ValueError, TypeError) as e:
print("Conversion error: {}".format(str(e)), file=sys.stderr)
return -1

We take advantage of the fact that exception objects can be converted to strings using the str() constructor.

Let's see that at the REPL:

>>> from exceptional import convert
>>> convert("fail")
Conversion error: invalid literal for int() with base 10: 'fail'
-1
..................Content has been hidden....................

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