Examples in Python 3
"""
Try-except example with string to integer conversion
"""
# The string is numeric - int() will succeed
x = "42"
print(x, "is of type", type(x))
try:
x = int(x)
print(x, "is of type", type(x))
except Exception:
print("Could not convert", x, "to integer")
print(x, "is the answer to everything\n")
# The string is not numeric - int() will fail and throw an exception
x = "fortytwo"
print(x, "is of type", type(x))
try:
x = int(x)
print(x, "is of type", type(x))
except Exception:
print("Could not convert", x, "to integer")
print(x, "is the answer to everything")
2014-07-17 (sylvanas) PA1 First try.