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

Community
  • 1
  • 1
helpermethod
  • 59,493
  • 71
  • 188
  • 276
  • 3
    This issue has been discussed in this question: http://stackoverflow.com/questions/855759/python-try-else – Tendayi Mawushe Oct 22 '10 at 11:31
  • 2
    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 http://stackoverflow.com/a/22579805/1503120 may also be useful. – jamadagni Mar 22 '14 at 18:11

3 Answers3

19

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.

Asclepius
  • 57,944
  • 17
  • 167
  • 143
3

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
  • 328,213
  • 58
  • 503
  • 561
  • 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 Oct 22 '10 at 12:09
3

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

Asclepius
  • 57,944
  • 17
  • 167
  • 143
knitti
  • 6,817
  • 31
  • 42