Resume after exception

metawilm at gmail.com metawilm at gmail.com
Tue Jun 14 09:16:19 EDT 2005


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

No, not in Python. The concept has however been discussed, under the
name "resumable exceptions".

http://www.google.com/search?num=100&q=%22resumable+exceptions%22+site%3Apython.org

An excellent article about the concept was written by Kent Pitman:

"Condition Handling in the Lisp Language Family"
http://www.nhplace.com/kent/Papers/Condition-Handling-2001.html

Common Lisp is a language that does have the feature. Your code would
be written in Lisp like below. When the function notices the file is
locked, it will raise an exception. Now imagine there are two ways to
solve the problem: 1) read the file anyway, despite the lock; 2) clear
the lock and read the file. Or reading the file could be cancelled.
These three possible ways to continue the execution are set up by
"restart-case". (So this is actually a generalization of your request,
in that instead of "just continueing", you can direct the way of
continuing)

(defun read-unlocked-file (file-name)
  (with-open-file (f file-name)

    (when (string= (read-line f) "FILE LOCKED")
      (let ((user "lock-user")
            (timestamp 123))
        (restart-case (error 'file-locked :name file-name
                             :user user :timestamp timestamp)
          (continue () :report "Continue reading the locked file.")
          (clear-lock () :report "Clear the lock and continue reading"
            (warn "clearing lock..."))
          (abort () :report "Abort reading the file."
            (return-from read-unlocked-file)))))

    (warn "reading remainder of file...")
    t))

When reading a locked file, you end up with this message:

CL-USER(31): (read-unlocked-file "file.txt")
Error: File file.txt was locked by lock-user at time 123.
  [condition type: FILE-LOCKED]

Restart actions (select using :continue):
 0: Continue reading the locked file.
 1: Clear the lock and continue reading
 2: Abort reading the file.
 3: Return to Top Level (an "abort" restart).
 4: Abort entirely from this process.

Note the three first "restart actions" are the ones we just defined
inside "read-unlocked-file". Let's continue execution by clearing the
lock (restart number 1):

[1] CL-USER(32): :continue 1
Warning: clearing lock...
Warning: reading remainder of file...
T

If Python had restarts, in your example you would set up code that,
depending on whether the user clicked "abort" or "continue" in the
dialog, automatically invokes the corresponding restart to either
continue or abort the calculation.

Restarts are pretty cool. Maybe Stackless Python could support it
fairly easily, restarts basically being named continuations?


- Willem




More information about the Python-list mailing list