Resume after exception

Peter Hansen peter at engcorp.com
Tue Jun 14 08:06:00 EDT 2005


Richard Lewis wrote:
> Is it possible to have an 'except' case which passes control back to the
> point after the exception occurred?

Basically no, although I could imagine some gross hack with the frame 
info and some bytecode hacks that effect a "goto".  Basically the stack 
frame gets unwound to the point where the exception is caught.  If you 
need recoverability, write your open_file function to be resumable in 
some way.

Note that you could easily (perhaps) implement this as a callable 
object, with the required state stored internally, and make the result 
almost indistinguishable from what you are asking for:

I could imagine an API allowing something like this:

open_file = RecoverableOpenFileThingy()

while not open_file.completed:
     try:
         open_file("foo.bar")
     except FileLockException, ex:
         # blah blah
         if ans != tkMessageBox.YES:
             open_file.completed = True

But since your open_file() doesn't seem likely to be doing anything 
particularly complicated, I really doubt you need the complexity of a 
special class here.  Just stick the relevant code inside a loop, much 
like that above, and break out of the loop when things succeed.

(What internal state do you think the open_file procedure would have to 
maintain, which you would be trying to resume?  If you are just going to 
go back to the beginning of it and try again, you don't need anything 
like what you asked for, just a regular loop.)



More information about the Python-list mailing list