Forcing a code stream to throw a block

I have:

try:
   ...
except Exception, e:
   print "Problem. %s" % str(e)

However, somewhere in the attempt, I will need to behave as if it were faced with an Exception. This is non-pythonic:

try:
   ...
   raise Exception, 'Type 1 error'
   ...

except Exception, e:
   print "Problem. Type 2 error %s" % str(e)
+5
source share
2 answers

I think this is a bad design. If you need to take any action if (and only if) an exception has not been thrown, this is what the proposal is else. If you need to unconditionally take some action, what is needed finally. here is a demo:

def myraise(arg):
    try:
        if arg:
            raise ValueError('arg is True')
    except ValueError as e:
        print(e)
    else:
        print('arg is False')
    finally:
        print("see this no matter what")

myraise(1)
myraise(0)

You need to specify an unconditional code on finallyand put other material in except/ elseas needed.

+5
source

, "unPythonic". ( ) , , , . try/except/else/finally :

try:
    #line which might fail
except ExceptionType: # the exception type which you are worried about
    #what to do if it raises the exception
else:
    #this gets done if try is successful
finally:
    #this gets done last in both cases (try successful or not)
+4

All Articles