try:
raise Exception("Oh no! An error happened!")
except Exception as err:
print("An error was handled")
finally:
print("This runs either way.")
try:
do_something()
except:
print "Caught it!"
# import module sys to get the type of exception
import sys
randomList = ['x', 0, 4]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print(sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pass
# import module sys to get the type of exception
import sys
randomList = ['x', 0, 4]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except Exception as e:
print(e.__class__, "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)