我试图从一个稍微不同的角度来回答这个问题。
OP的问题有两部分,我也添加了第三部分。
try-except-else存在的原因是什么?
try-except-else模式,或者一般的Python,是否鼓励在流控制中使用异常?
什么时候使用异常呢?
问题1:try-except-else存在的原因是什么?
这个问题可以从战术的角度来回答。当然有理由去尝试……存在。这里唯一的新添加是else…子句,它的有用性归结为它的独特性:
It runs an extra code block ONLY WHEN there was no exception happened in the try... block.
It runs that extra code block, OUTSIDE of the try... block (meaning any potential exceptions happen inside the else... block would NOT be caught).
It runs that extra code block BEFORE the final... finalization.
db = open(...)
try:
db.insert(something)
except Exception:
db.rollback()
logging.exception('Failing: %s, db is ROLLED BACK', something)
else:
db.commit()
logging.info(
'Successful: %d', # <-- For the sake of demonstration,
# there is a typo %d here to trigger an exception.
# If you move this section into the try... block,
# the flow would unnecessarily go to the rollback path.
something)
finally:
db.close()
In the example above, you can't move that successful log line into behind the finally... block. You can't quite move it into inside the try... block, either, due to the potential exception inside the else... block.
问题2:Python是否鼓励使用异常进行流控制?
我没有找到任何官方书面文件来支持这种说法。(对于不同意的读者,请留下评论,并附上你找到的证据链接。)我找到的唯一一个模糊相关的段落是EAFP术语:
EAFP
请求原谅比请求允许容易。这种常见的Python编码风格假设存在有效的键或属性,并在假设为假时捕获异常。这种简洁快速的风格的特点是存在许多try和except语句。该技术与许多其他语言(如C)常见的LBYL风格形成对比。
这一段只是描述,而不是这样做:
def make_some_noise(speaker):
if hasattr(speaker, "quack"):
speaker.quack()
我们更喜欢这样:
def make_some_noise(speaker):
try:
speaker.quack()
except AttributeError:
logger.warning("This speaker is not a duck")
make_some_noise(DonaldDuck()) # This would work
make_some_noise(DonaldTrump()) # This would trigger exception
或者甚至可能省略try…除了:
def make_some_noise(duck):
duck.quack()
因此,EAFP鼓励鸭子打字。但是它不鼓励使用异常进行流控制。
问题3:在什么情况下,应该将程序设计为发出异常?
使用异常作为控制流是否是反模式,这是一个有争议的话题。因为,一旦为给定函数做出了设计决策,它的使用模式也将被确定,然后调用者将别无选择,只能以这种方式使用它。
因此,让我们回到基本原理,看看函数何时通过返回值或发出异常更好地产生结果。
返回值和异常之间的区别是什么?
Their "blast radius" are different. Return value is only available to the immediate caller; exception can be automatically relayed for unlimited distance until it is caught.
Their distribution patterns are different. Return value is by definition one piece of data (even though you could return a compound data type such as a dictionary or a container object, it is still technically one value).
The exception mechanism, on the contrary, allows multiple values (one at a time) to be returned via their respective dedicate channel. Here, each except FooError: ... and except BarError: ... block is considered as its own dedicate channel.
因此,使用一种合适的机制取决于每个不同的场景。
All normal cases should better be returned via return value, because the callers would most likely need to use that return value immediately. The return-value approach also allows nesting layers of callers in a functional programming style. The exception mechanism's long blast radius and multiple channels do not help here.
For example, it would be unintuitive if any function named get_something(...) produces its happy path result as an exception. (This is not really a contrived example. There is one practice to implement BinaryTree.Search(value) to use exception to ship the value back in the middle of a deep recursion.)
If the caller would likely forget to handle the error sentinel from the return value, it is probably a good idea to use exception's characterist #2 to save caller from its hidden bug. A typical non-example would be the position = find_string(haystack, needle), unfortunately its return value of -1 or null would tend to cause a bug in the caller.
If the error sentinel would collide with a normal value in the result namespace, it is almost certain to use an exception, because you'd have to use a different channel to convey that error.
If the normal channel i.e. the return value is already used in the happy-path, AND the happy-path does NOT have sophisicated flow control, you have no choice but to use exception for flow control. People keep talking about how Python uses StopIteration exception for iteration termination, and use it to kind of justify "using exception for flow control". But IMHO this is only a practical choice in a particular situation, it does not generalize and glorify "using exception for flow control".
At this point, if you already make a sound decision on whether your function get_stock_price() would produce only return-value or also raise exceptions, or if that function is provided by an existing library so that its behavior has long be decided, you do not have much choice in writing its caller calculate_market_trend(). Whether to use get_stock_price()'s exception to control the flow in your calculate_market_trend() is merely a matter of whether your business logic requires you to do so. If yes, do it; otherwise, let the exception bubble up to a higher level (this utilizes the characteristic #1 "long blast radius" of exception).
In particular, if you are implementing a middle-layer library Foo and you happen to be making a dependency on lower-level library Bar, you would probably want to hide your implementation detail, by catching all Bar.ThisError, Bar.ThatError, ..., and map them into Foo.GenericError. In this case, the long blast radius is actually working against us, so you might hope "only if library Bar were returning its errors via return values". But then again, that decision has long been made in Bar, so you can just live with it.
总之,我认为是否使用异常作为控制流是一个有争议的问题。