3
votes

Possible Duplicate:
Python try-else

Comming from a Java background, I don't quite get what the else clause is good for.

According to the docs

It is useful for code that must be executed if the try clause does not raise an exception.

But why not put the code after the try block? It seems im missing something important here...

3
This issue has been discussed in this question: stackoverflow.com/questions/855759/python-try-else - Tendayi Mawushe
While many people have tagged this as a dup of the above question, it doesn't really seem to address the difference the OP asks about here i.e. between putting after the try block and within the else clause. AndrewBC's reply below answers that much better. My contribution stackoverflow.com/a/22579805/1503120 may also be useful. - jamadagni

3 Answers

15
votes

The else clause is useful specifically because you then know that the code in the try suite was successful. For instance:

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
    else:
        print arg, 'has', len(f.readlines()), 'lines'
        f.close()

You can perform operations on f safely, because you know that its assignment succeeded. If the code was simply after the try ... except, you may not have an f.

3
votes

Consider

try:
    a = 1/0
except ZeroDivisionError:
    print "Division by zero not allowed."
else:
    print "In this universe, division by zero is allowed."

What would happen if you put the second print outside of the try/except/else block?

3
votes

It is for code you want to execute only when no exception was raised.