Question

I am developing a program in python and have reached a point I don't know how to solve. My intention is to use a with statement, an avoid the usage of try/except.

So far, my idea is being able to use the continue statement as it would be used inside the except. However, I don't seem to succeed.

Let's supposse this is my code:

def A(object):
    def __enter__:
        return self

    def __exit__:
        return True

with A():
    print "Ok"
    raise Exception("Excp")
    print "I want to get here"

print "Outside"

Reading the docs I have found out that by returning True inside the __exit__ method, I can prevent the exception from passing, as with the pass statement. However, this will immediately skip everything left to do in the with, which I'm trying to avoid as I want everything to be executed, even if an exception is raised.

So far I haven't been able to find a way to do this. Any advice would be appreciated. Thank you very much.

Was it helpful?

Solution

It's not possible.

The only two options are (a) let the exception propagate by returning a false-y value or (b) swallow the exception by returning True. There is no way to resume the code block from where the exception was thrown. Either way, your with block is over.

OTHER TIPS

You can't. The with statement's purpose is to handle cleanup automatically (which is why exceptions can be suppressed when exiting it), not to act as Visual Basic's infamous On Error Resume Next.

If you want to continue the execution of a block after an exception is raised, you need to wrap whatever raises the exception in a try/except statement.

Though most of the answers are correct, I'm afraid none suits my problem (I know I didn't provide my whole code, sorry about that).

I've solved the problem taking another approach. I wanted to be able to handle a NameError ("variable not declared") inside a With. If that occurred, I would look inside my object for that variable, and continue.

I'm now using globals() to declare the variable. It's not the best, but it actually works and let's the with continue as no exception is being risen.

Thank you all!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top