else clause in try statement… what is it good for [duplicate]

南楼画角 提交于 2019-12-13 14:12:40

问题


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


回答1:


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.




回答2:


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:


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



来源:https://stackoverflow.com/questions/3996329/else-clause-in-try-statement-what-is-it-good-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!