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