python3 try except all errors code example
Example 1: how to print error in try except python
try:
except Exception as e:
print("ERROR : "+str(e))
Example 2: python catch all exceptions
try:
raise Exception("Oh no! An error happened!")
except Exception as err:
print("An error was handled")
finally:
print("This runs either way.")
Example 3: catch error python
import traceback
dict = {'a':3,'b':5,'c':8}
try:
print(dict[q])
except:
traceback.print_exc()
Example 4: catch error data with except python
import sys
try:
S = 1/0
except:
e = sys.exc_info()
print(e)
try:
S = 1/0
except ZeroDivisionError as e:
print(e)
Example 5: python defualt error handler
import sys
def my_except_hook(exctype, value, traceback):
if exctype == KeyboardInterrupt:
print "Handler code goes here"
else:
sys.__excepthook__(exctype, value, traceback)
sys.excepthook = my_except_hook