views:

61

answers:

3

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

+2  A: 

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?

Tim Pietzcker
It's also better than putting it after the assignment to `a`, before the `except` —which would be equivalent to this example— because it prevents catching of unwanted exceptions.
intuited
+2  A: 

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

knitti
+1  A: 

The else clause is useful specifically because you then know that the code in the try suite was successful, so, 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.

AndrewBC