开发者

running code if try statements were successful in python

开发者 https://www.devze.com 2022-12-29 08:04 出处:网络
I was wondering if in python there was a simple way to run code if a try statement was successful that wasn\'t in the try statement itself. Is that what the else or finally commands do (I didn\'t unde

I was wondering if in python there was a simple way to run code if a try statement was successful that wasn't in the try statement itself. Is that what the else or finally commands do (I didn't understand their documentation)? I know I could use code like this:

successful = False
try:
    #code that might fail
    successful = True
except:
    #error handling if c开发者_如何学Pythonode failed
if successful:
    #code to run if try was successful that isn't part of try

but I was wondering if there was a shorter way.


You want else:

for i in [0, 1]:
    try:
        print '10 / %i: ' % i, 10 / i
    except:
        print 'Uh-Oh'
    else:
        print 'Yay!'


You are looking for the else keyword:

try:
    #code that might fail
except SomeException:
    #error handling if code failed
else:
    # do this if no exception occured


Your try block should be the code you want to execute, and your except should be killing the program. I'd need to understand your object better to give a better answer.

In OO programming, you want to "Tell, don't ask" so keep all the logic that should happen in the try block, and then your error handling in the except block.

0

精彩评论

暂无评论...
验证码 换一张
取 消