|
|
|||||||||||||||
|
|
ExceptionsThis is Chapter 8 section 8.2.The exception construct: a mechanism in programming languages for jumping from one point of execution to code associated with an earlier program block (the handler). A value may be passed to the handler. Terminology: exceptions are raised or thrown; handled or caught. Purpose: exceptions allow a function implementor to do a couple of things:
Exception mechanisms in different languages vary in detail such as what is thrown:
But you always find
Exceptions are handled by the (dynamically) most recent matching handler. Exceptions handlers are a form of dynamic scoping even in statically scoped languages. Follow the dynamic links in the stack to find most recent handler (or try-finally). Some languages offer a finally clause in which you put code to be executed after a block completes, whether it completes normally, a result of return, continue or break, or by raising an an exception. The exception need not be handled in the block associated with the finally clause: it could just be "passing by" on its way to a higher exception handler. Python exceptionstry: suite 1 [except [exception [, value]]: suite 2]+ [else: suite 3]is a try block with multiple handlers. (Note the square brackets here are meta-characters used to indicate repeating and optional syntactic elements. They are not actually included in Python programs.) When an exception is raised in suite 1, the first of the suite 2s that match the exception is executed. If none of the handlers match the system continues looking in this blocks caller for a match. If no exception occurs in suite 1, suite 3 is executed when suite 1 completes. Try-finally is a way to make sure that some code is executed regardless of whether or not an exception is raised in another block of code. try: suite 1 finally: suite 2If an unhandled exception occurs in suite 1, suite 2 is executed and then the exception is re-raised for handling by higher-level code. There are lots of details such as: what happens if suite 2 itself does a return or break? Exception is lost Try-finally solves the problem of how to deallocate resources owned by a frame that is thrown away because of a lower-level exception. Modern languages already have some automatic help for this problem:
|
||||||||||||||
| (c) 2003 Curtis Dyreson, (c) 2004 Carl H. Hauser E-mail questions or comments to Prof. Carl Hauser | ||||||||||||||||