python try except code example

Example 1: how to print error in try except python

try:
  # some code
except Exception as e:
	print("ERROR : "+str(e))

Example 2: throwing an exception python

raise Exception("message")

Example 3: exception pyton print

except Exception as e: print(e)

Example 4: python try except

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

Example 5: python try except

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

Example 6: python try except

try:
  print("I will try to print this line of code")
except Exception as e:
  print(f"Error message: {}")

Tags:

Java Example