在Python中使用try-except-else是个好习惯吗? [英] Is it a good practice to use try-except-else in Python?

查看:117
本文介绍了在Python中使用try-except-else是个好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  try:
try_this(whatever)
除了SomeException作为例外:
#Handle exception
else:
return something

尝试除了否则存在的原因是什么?



我不喜欢这种编程,因为它使用异常来执行流控制。但是,如果它被包含在语言中,那就必须有很好的理由,不是吗?



我的理解是,异常不是错误,并且它们应该仅用于异常条件(例如,我尝试将文件写入磁盘,没有更多的空间,或者我没有权限),而不是用于流控制。



通常我处理例外:

  something = some_default_value 
try:
something = try_this(whatever)
除了SomeException作为例外:
#Handle异常
finally:
返回的东西

或者如果我真的不想返回任何异常,那么:




something = try_this(whatever)
return something
除了SomeException作为例外:
#Handle exception


解决方案


我不知道是否出于无知,但我不喜欢这种
的编程,因为它使用异常来执行流控制。


在Python世界中,使用例外来进行流量控制是常见的和正常的。



即使是Python核心开发人员使用流程控制的异常,而且这种风格很大感谢语言(即迭代器协议使用 StopIteration 信号循环终止)。



此外,try-except-style用于防止某些look-before-you-leap构造。例如,测试 os.path.exists 会导致在使用它时可能已过期的信息。同样, Queue.full 返回可能陈旧的信息。在这些情况下,尝试除外样式将会生成更可靠的代码


我的理解是异常不是错误,他们应该只有
用于特殊条件


在其他一些语言中,该规则反映了他们的图书馆的文化规范。 规则也部分地基于这些语言的性能考虑。



Python文化规范有些不同。在许多情况下,您必须使用控制流的异常。此外,在Python中使用异常并不会像在一些编译语言中一样减慢周围的代码和调用代码(即,CPython已经实现了在每一步都进行异常检查的代码,无论实际是否使用异常)。 p>

换句话说,你的理解是例外是特殊的是一种在某些其他语言中是有意义的规则,但不适用于Python。


但是,如果它包含在语言本身中,则必须有一个
很好的理由,不是吗?


除了帮助避免竞争条件外,异常对于拉出错误处理外部循环也是非常有用的。这是解释型语言中必不可少的优化,这些语言不会自动循环不变代码运动



此外,异常可以在常见的情况下简化代码,其中处理问题的能力远离出现问题的位置。例如,通常有业务逻辑的顶级用户界面代码调用代码,这又调用低级例程。在低级例程中出现的情况(例如数据库访问中唯一键的重复记录)只能在顶级代码中处理(例如向用户询问与现有键不冲突的新密钥)。对于这种控制流使用异常,允许中级例程完全忽略该问题,并从流量控制的方面很好地解耦。



是一个不错的博客文章不可缺少例外情况



另请参阅StackOverFlow答案:是异常真正的异常错误吗?


这是什么原因try-except-else存在?


else子句本身很有趣。当没有例外但在finally子句之前运行它。这是它的主要目的。



没有else子句,在完成之前运行附加代码的唯一选项是将代码添加到try子句中的笨拙习惯。这是笨拙的,因为它有风险
提高了不受try块保护的代码中的异常。



运行附加的用例最终确定之前的未受保护的代码不会经常出现。所以,不要指望在发布的代码中看到很多例子。



else子句的另一个用例是执行不发生异常时必须发生的操作,并且在处理异常时不发生。例如:

  recip = float('Inf')
try:
recip = 1 / f (x)
除了ZeroDivisionError:
logging.info('Infinite result')
else:
logging.info('Finite result')

最后,try-block中else子句的最常用的方法是进行一些美化(将异常结果和非 - 同一水平的缩进的显着结果)。这种使用总是可选的,并不是绝对必要的。


From time to time in Python, I see the block:

try:
   try_this(whatever)
except SomeException as exception:
   #Handle exception
else:
   return something

What is the reason for the try-except-else to exist?

I do not like that kind of programming, as it is using exceptions to perform flow control. However, if it is included in the language, there must be a good reason for it, isn't it?

It is my understanding that exceptions are not errors, and that they should only be used for exceptional conditions (e.g. I try to write a file into disk and there is no more space, or maybe I do not have permission), and not for flow control.

Normally I handle exceptions as:

something = some_default_value
try:
    something = try_this(whatever)
except SomeException as exception:
    #Handle exception
finally:
    return something

Or if I really do not want to return anything if an exception happens, then:

try:
    something = try_this(whatever)
    return something
except SomeException as exception:
    #Handle exception

解决方案

"I do not know if it is out of ignorance, but I do not like that kind of programming, as it is using exceptions to perform flow control."

In the Python world, using exceptions for flow control is common and normal.

Even the Python core developers use exceptions for flow-control and that style is heavily baked into the language (i.e. the iterator protocol uses StopIteration to signal loop termination).

In addition, the try-except-style is used to prevent the race-conditions inherent in some of the "look-before-you-leap" constructs. For example, testing os.path.exists results in information that may be out-of-date by the time you use it. Likewise, Queue.full returns information that may be stale. The try-except-else style will produce more reliable code in these cases.

"It my understanding that exceptions are not errors, they should only be used for exceptional conditions"

In some other languages, that rule reflects their cultural norms as reflected in their libraries. The "rule" is also based in-part on performance considerations for those languages.

The Python cultural norm is somewhat different. In many cases, you must use exceptions for control-flow. Also, the use of exceptions in Python does not slow the surrounding code and calling code as it does in some compiled languages (i.e. CPython already implements code for exception checking at every step, regardless of whether you actually use exceptions or not).

In other words, your understanding that "exceptions are for the exceptional" is a rule that makes sense in some other languages, but not for Python.

"However, if it is included in the language itself, there must be a good reason for it, isn't it?"

Besides helping to avoid race-conditions, exceptions are also very useful for pulling error-handling outside loops. This is a necessary optimization in interpreted languages which do not tend to have automatic loop invariant code motion.

Also, exceptions can simplify code quite a bit in common situations where the ability to handle an issue is far removed from where the issue arose. For example, it is common to have top level user-interface code calling code for business logic which in turn calls low-level routines. Situations arising in the low-level routines (such as duplicate records for unique keys in database accesses) can only be handled in top-level code (such as asking the user for a new key that doesn't conflict with existing keys). The use of exceptions for this kind of control-flow allows the mid-level routines to completely ignore the issue and be nicely decoupled from that aspect of flow-control.

There is a nice blog post on the indispensibility of exceptions here.

Also, see this StackOverFlow answer: Are exceptions really for exceptional errors?

"What is the reason for the try-except-else to exist?"

The else-clause itself is interesting. It runs when there is no exception but before the finally-clause. That is its primary purpose.

Without the else-clause, the only option to run additional code before finalization would be the clumsy practice of adding the code to the try-clause. That is clumsy because it risks raising exceptions in code that wasn't intended to be protected by the try-block.

The use-case of running additional unprotected code prior to finalization doesn't arise very often. So, don't expect to see many examples in published code. It is somewhat rare.

Another use-case for the else-clause is to perform actions that must occur when no exception occurs and that do not occur when exceptions are handled. For example:

   recip = float('Inf')
   try:
       recip = 1 / f(x)
   except ZeroDivisionError:
       logging.info('Infinite result')
   else:
       logging.info('Finite result')

Lastly, the most common use of an else-clause in a try-block is for a bit of beautification (aligning the exceptional outcomes and non-exceptional outcomes at the same level of indentation). This use is always optional and isn't strictly necessary.

这篇关于在Python中使用try-except-else是个好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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