running code if try statements were successful in python

Question:

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 code 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.

Asked By: None

||

Answers:

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
Answered By: unutbu

You want else:

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

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.

Answered By: Zee Spencer
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.