10 The stack
Caltech CS 1: Fall 2014 Functions calling functions def func2 (a, b): return (110) def func3(n): return (3 * n + 10) func2(10, 20) returns 110 The frame for func2 is removed ("popped") from the stack Now the stack is empty The stack
Caltech CS 1: Fall 2014
Caltech CS 1: Fall 2014 What about exceptions? How does any of this relate to exception handling? We'll see after the break...
Caltech CS 1: Fall 2014 Interlude It's insanely great!
Caltech CS 1: Fall 2014 Recall We have a function called sum_numbers_in_file It takes a filename, returns a number Can raise an IOError exception if the file with the filename doesn't exist Can raise a ValueError exception if the file has lines without numbers Don't want to handle these exceptions in the function itself • too many different ways to do it
Caltech CS 1: Fall 2014 "Remote" exception handling We won't have a try block inside the sum_numbers_in_file function We will have a try block inside the function that calls the sum_numbers_in_file function • (actually, doesn't have to be inside a function) Let's write two different functions that call sum_numbers_in_file and handle the possible exceptions
Caltech CS 1: Fall 2014 Function #1 This function will try to run sum_numbers_in_file on a single filename If an exception happens, it will prompt for a new filename and will try again If no exception happens, it will return the sum of the numbers in the file
Caltech CS 1: Fall 2014 Function #1 def sum_numbers_in_file_interactive (filename): while True: try: total = sum_numbers_in_file (filename) return total except IOError: print 'Couldn't read file: %s' % filename filename = raw_input('Enter new filename: ') except ValueError: print 'Invalid line in file: %s' % filename filename = raw_input("Enter new filename: ')
Caltech CS 1: Fall 2014 Function #1 In this function, sum_numbers_in_file is called inside a try block If an exception is raised during the execution of sum_numbers_in_file , it will not be caught in that function Instead, the exception will go back down in the runtime stack to the function that called it ( sum_numbers_in_file_interactive ) And it will get handled inside the try / except block of this function
Caltech CS 1: Fall 2014 Function #1 This function will continue to run sum_numbers_on_file on every filename supplied by the user until a valid filename is given • i.e. a filename for which a sum can be computed Once a sum is computed, the function will return • which breaks us out of the while True: loop
Caltech CS 1: Fall 2014 Exceptions and the stack
You've reached the end of your free preview.
Want to read all 75 pages?
- Fall '08
- Computer Programming, Subroutine, Call stack, Control flow, Caltech CS, func2