running code if try statements were successful in python

36,474

Solution 1

You want else:

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

Solution 2

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
Share:
36,474
None
Author by

None

I am nothing.

Updated on February 25, 2021

Comments

  • None
    None about 3 years

    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.

  • Mike Graham
    Mike Graham about 14 years
    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.
  • Zee Spencer
    Zee Spencer about 14 years
    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...