resume execution after catching with an excepthook?

Chris Angelico rosuav at gmail.com
Thu Oct 25 10:51:43 EDT 2012


On Thu, Oct 25, 2012 at 12:15 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> I don't believe that there is any
> way to jump back to the line of code that just failed (and why would you,
> it will just fail again)

There are several reasons to retry something after an exception,
mainly if some external state gets changed. Virtual memory is usually
implemented using traps, so the OS handles an interrupt by paging
something in from the disk, then retrying the "failing" instruction.
The old-favorite "Abort, retry, ignore[, fail]?" prompt from DOS has
the same notion; you tried to save a file onto a write-protected
floppy disk, an exception is thrown, you handle the exception by
getting the user to unprotect or change disks, and you resume where
you left off. CPU-level interrupts always have a return address for
that exact reason.

Handling Ctrl-C in this way makes a lot of sense. Give the user the
option to try to abort, but then to optionally change his/her mind and
keep going. Or possibly have a third option: break out of the current
operation and go back to some primary loop (throw the exception and
let it be caught at the main loop).

Arguably the problem here is that KeyboardInterrupt is an exception.
Perhaps a more classic signal handling structure should be used: when
signal received, call function. That function then has the power to
raise an exception, which will propagate through whatever code is
currently executing. This sort of thing would have all the usual
dangers of signal handlers, though; you have NO IDEA what state the
program's in, so you have to be ubercareful of what globals you use or
change.

ChrisA



More information about the Python-list mailing list