Handouts Lecture8 1
Handouts Lecture8 1
Types of exceptions
Already seen common error types:
SyntaxError: Python cant parse program
NameError: local or global name not found
AttributeError: attribute reference fails
TypeError: operand doesnt have correct type
ValueError: operand type okay, but value is illegal
IOError: IO system reports malfunction (e.g. file
not found)
finally:
Body of this clause is always executed after try,
else and except clauses, even if they raised
another error or executed a break, continue or
return
Useful for clean-up code that should be run no matter
what else happened (e.g. close file)
An example
def divide(x, y):
try:
result = x / y
except ZeroDivisionError, e:
print "division by zero! " + str(e)
else:
print "result is", result
finally:
print "executing finally clause"
An example, revised
def divideNew(x, y):
try:
result = x / y
except ZeroDivisionError, e:
print "division by zero! " + str(e)
except TypeError:
divideNew(int(x), int(y))
else:
print "result is", result
finally:
print "executing finally clause"