else语句在try语句中什么是有益的 [英] else clause in try statement... what is it good for

查看:128
本文介绍了else语句在try语句中什么是有益的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Python try-else

从Java背景来看,我不相当得到什么 else 子句是有益的。

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

根据文档


如果try子句没有
引发异常,则必须执行
的代码是有用的。

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

但是为什么不把代码放在try块之后呢?似乎在这里缺少一些重要的东西...

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

推荐答案

else 子句特别有用,因为您知道尝试套件中的代码是成功的。例如:

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()

您可以对 f 安全地,因为你知道它的分配成功了。如果代码只是在try ...之后,除了你可能没有一个 f

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.

这篇关于else语句在try语句中什么是有益的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆