61A Lecture 25Friday, October 28Friday, October 28, 2011From Last Time: Adjoining to a Tree Set2531 791187911878Right! Left! Right!None None8NoneStop!87879118531 79118Friday, October 28, 2011From the Exam: Pruned Trees3a b c dTrue True False(a,b) (a,c) (a,d)prunedFriday, October 28, 2011From the Exam: Pruned Trees4pruned(a, c)pruned(a.right, c.right)a cimplieswhat about c.left?NoneNoneNone NoneFriday, October 28, 2011From the Exam: Pruned Trees5pruned(a, d)pruned(a.left, d.left)awould implydNoneNoneNone Not NoneFriday, October 28, 2011From the Exam: Pruned Trees6def pruned(t1, t2): if t2 is None: return True if t1 is None: return False return pruned(t1.left, t2.left) and pruned(t1.right, t2.right)a b c dRecursive call: both branches are pruned as wellBase cases: one (or more) of the trees is NoneFriday, October 28, 2011Today's Topic: Handling ErrorsSometimes, computers don't do exactly what we expect•A function receives unexpected argument types•Some resource (such as a file) does not exist•Network connections are lost7Grace Hopper's Notebook, 1947, Moth found in a Mark II ComputerFriday, October 28, 2011Different Error Handling Policies8VersusFriday, October 28, 2011ExceptionsA built-in mechanism in a programming language to declare and respond to exceptional conditionsPython raises an exception whenever an error occursExceptions can be handled by the program, preventing a crashUnhandled exceptions will cause Python to halt execution9Exceptions are objects! They have classes with constructors.They enable non-local continuations of control:If f calls g and g calls h, exceptions can shift control from h to f without waiting for g to return.However, exception handling tends to be slow.Mastering exceptions:Friday, October 28, 2011Assert StatementsAssert statements raise an exception of type AssertionError10assert <expression>, <string>Assertions are designed to be used liberally and then disabled in "production" systems. "O" stands for optimized.python3 -OWhether assertions are enabled is governed by a bool __debug__DemoFriday, October 28, 2011Raise StatementsExceptions are raised with a raise statement.11raise <expression><expression> must evaluate to an exception instance or class.Exceptions are constructed like any other object; they are just instances of classes that inherit from BaseException.TypeError -- A function was passed the wrong number/type of argumentNameError -- A name wasn't foundKeyError -- A key wasn't found in a dictionaryRuntimeError -- Catch-all for troubles during interpretationFriday, October 28, 2011Try StatementsTry statements handle exceptions12try: <try suite>except <exception class> as <name>: <except suite>...Execution rule:The <try suite> is executed first;If, during the course of executing the <try suite>, an exception is raised that is not handled otherwise, andIf the class of the exception inherits from <exception class>, thenThe <except suite> is executed, with <name> bound to the exceptionFriday, October 28, 2011Handling ExceptionsException handling can prevent a program from terminating13>>> try: x = 1/0 except ZeroDivisionError as e: print('handling a', type(e)) x = 0handling a <class 'ZeroDivisionError'>>>> x0Multiple try statements: Control jumps to the except suite of the most recent try statement that handles that type of exception.DemoFriday, October 28, 2011WWPD: What Would Python Do?How will the Python interpreter respond?14 >>> invert_safe(1/0) >>> try: invert_safe(0) except ZeroDivisionError as e: print('Handled!') >>> inverrrrt_safe(1/0)def invert(x): result = 1/x # Raises a ZeroDivisionError if x is 0 print('Never printed if x is 0') return resultdef invert_safe(x): try: return invert(x) except ZeroDivisionError as e: return str(e)Friday, October 28, 2011Example: Safe Iterative ImprovementIterative improvement is a higher-order function•The update argument provides better guesses•The done argument indicates completion•Used to implement Newton's method (find_root)15newton.py Page 2 3.0 """ def update(guess): return cube_root_update(guess, x) def done(guess): return guess * guess * guess == x return iter_improve(update, done)def square_root_newton(x): """Return the square root of x. >>> square_root_newton(9) 3.0 """ return find_root(lambda y: y * y é x) def cube_root_newton(x): """Return the cube root of x. >>> cube_root_newton(27) 3.0 """ return find_root(lambda y: y * y * y é x) def approx_derivative(f, x, delta=1eé5): """Return an approximation to the derivative of f at x.""" df = f(x + delta) é f(x) return df/deltadef newton_update(f): """Return an update function for f using Newton's method.""" def update(x): return x é f(x) / approx_derivative(f, x) return updatedef find_root(f, guess=1): """Return a guess of a zero of the function f, near guess. >>> from math import sin >>> find_root(lambda y: sin(y), 3) 3.141592653589793 """ return iter_improve(newton_update(f), lambda x: f(x) == 0, guess)@maindef run(): interact()newton.py Page 2 3.0 """ def update(guess): return cube_root_update(guess, x) def done(guess): return guess * guess * guess == x return iter_improve(update, done)def square_root_newton(x): """Return the square root of x. >>> square_root_newton(9) 3.0 """ return find_root(lambda y: y * y é x) def cube_root_newton(x): """Return the cube root of x. >>> cube_root_newton(27) 3.0 """ return find_root(lambda y: y * y * y é x) def approx_derivative(f, x, delta=1eé5): """Return an approximation to the derivative of f at x.""" df = f(x + delta) é f(x) return df/deltadef newton_update(f): """Return an update function for f using Newton's method.""" def update(x): return x é f(x) / approx_derivative(f, x) return updatedef find_root(f, guess=1): """Return a guess of a zero of the function f, near guess. >>> from math import sin >>> find_root(lambda y: sin(y), 3) 3.141592653589793 """ return iter_improve(newton_update(f), lambda x: f(x) == 0, guess)@maindef run(): interact()Friday, October 28, 2011Exception ChainingThe except suite of a try statement can raise another
View Full Document