python except else code example

Example 1: exception pyton print

except Exception as e: print(e)

Example 2: raise python

# Raise is used to cause an error
raise(Exception("Put whatever you want here!"))
raise(TypeError)

Example 3: python try else

try:
   # Code to test / execute
   print('Test')
except (SyntaxError, IndexError) as E:  # specific exceptions
   # Code in case of SyntaxError for example
   print('Synthax or index error !')
except:
   # Code for any other exception
   print('Other error !')
else:
   # Code if no exception caught
   print('No error')
finally:
   # Code executed after try block (success) or any exception (ie everytime)
   print('Done')

# This code is out of try / catch bloc
print('Anything else')

Example 4: python try else

try:
    a=2*3
except TypeError:
    print("Exception raised")
else:
    print("Everything is ok.")

Example 5: try except python

def sum_of(x, y):
  try:
    print(x + y)
  except TypeError:
    print("Invalid argument specified.")