views:

97

answers:

3

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.

+3  A: 

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
unutbu
+9  A: 

You want "else":

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

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.

Zachary Spencer
I don't think I tend to agree with this answer. "your except should be killing the program" is especially hard for me to swallow; we have exception handling so we can, well, handle exceptions. This is especially true in Python where exceptions are used liberally and for things like finishing iterating over an iterator, an event that 99% of the time is not a program-ending condition. I would not come anywhere near a blanket dismissal of else blocks on try/except, where only upon success you proceed to do something. Among other things, else often helps keep try blocks short, which is great.
Mike Graham
You're absolutely right. I've been writing test code for the past 3 weeks and approached it from the perspective that if something fails I want the test framework to know.I still have a hard time grokking the need for an else block, it seems to disrupt the flow of "Try to do this thing... If it fails, handle it" Shouldn't everything that should happen in the event there is no failure in the "Try to do this thing" section? Now you have logic here, then interrupting logic, and then logic after the interruption that should occur ONLY if the interruption doesn't occur...
Zachary Spencer