resume execution after catching with an excepthook?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Oct 25 11:40:44 EDT 2012


On Fri, 26 Oct 2012 01:51:43 +1100, Chris Angelico wrote:

> 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, 

I'm sure there are, but you're taking my point out of context. 

Andrea described his problem as *continuing*, not *re-trying*. I 
understand that re-trying operations is useful:

while True:
    try:
        some_operation()
    except SomeException:
        if not retry():
            break  # or raise an exception, or return


but I wouldn't describe that as "continuing", as Andrea did. I understand 
that as:

try:
    operation(1)
    operation(2)
    operation(3)
    operation(4)
    # and so forth...
except SomeException:
    if retry():
        # Magically jump back to the operation that was
        # active when the exception occurred.
        magic_happens_here()


If you could guarantee that each operation(N) was atomic ("all or 
nothing" -- it either succeeds, or has no effect) then such a feature 
would be useful. But as far as I know, you can't jump back into a try 
block from the except block, and even if you could, what's to stop the 
operation from failing again and again and again?
        
In Andrea's case, the failure he is worried about is "oops, I hit Ctrl-C 
when I actually wanted to not hit Ctrl-C", so presumably the failure 
wouldn't reoccur if you could jump backwards. But in any case, I can see 
no obvious way to make it work.

The python debugger pdb has a "jump" command that allows you to step 
backwards and re-execute code under certain conditions, so perhaps it is 
not quite impossible.

(I'm tempted to reply that the actual solution to this problem of 
accidentally hitting Ctrl-C is "well don't do that then".)



-- 
Steven



More information about the Python-list mailing list