3

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.

3
  • You can use warnings But with exceptions this is not possible I fear. Commented Nov 29, 2013 at 15:55
  • 1
    I'm probably going to regret asking this, but why do you want to avoid try/except? You seem to want to reimplement the finally clause from try/except, which makes me wonder why you don't just implement your with clause as a try/except statement. Commented Nov 29, 2013 at 15:56
  • 1
    When __exit__ is called, that is it. You've exited the context. You cannot get back in. Commented Nov 29, 2013 at 15:58

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.