error exception python numbers code example
Example 1: print type of exception python
try:
someFunction()
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
print (message)
Example 2: python catch int conversion error
>>> for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
... try:
... print('%s as an int is %d' % (str(value), int(value)))
... except ValueError as ex:
... print('"%s" cannot be converted to an int: %s' % (value, ex))
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'