return error python code example

Example 1: throwing an exception python

raise Exception("message")

Example 2: 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 3: catch error python

import traceback

dict = {'a':3,'b':5,'c':8}
try:
  print(dict[q])
 
except:
  traceback.print_exc()
  
# This will trace you back to the line where everything went wrong. 
# So in this case you will get back line 5

Example 4: python try except

try:
  val = 1/0 
except Exception as e:
  raise Exception('ZeroDivisionError')

Example 5: python exception

try:
  # code block
except ValueError as ve:
  print(ve)

Example 6: try pass python

except:
    pass