#!/usr/bin/env python3
import math

def myLog(x):
  if not type(x) is float:
     raise TypeError("only myLog(x) if x is float")
  if x <= 0:
     raise Exception("only myLog(x) when x>0")
  return math.log(x)


print("************************")
print("basic exception handling")
print("************************")
try:
  print(x)
except NameError:
  print("undefined variable")
except:
  print("something went wrong")

print()
print("*******************************************")
print("catching user-defined exceptions / messages")
print("*******************************************")
try:
  myLog(0.0)
except TypeError as message:
  print("a type error occured: " + str(message))
except Exception as message:
  print("something went wrong: "   + str(message)) 
else:
  print("nothing went wrong")
finally:                                  # always executed
  print("'try except finally' finished")

print()
print("***********************")
print("input/output exceptions")
print("***********************")
fileName = "demo.txt"
try:
  f = open(fileName)                      # default, reading only
  try:
    f.write("Lorum Ipsum")
  except:
    print("failed to write to " + fileName)
  finally:
    f.close()
except:
  print("failed opening of " + fileName)
