使用“例外除外”;与“除外...加薪”在Python中 [英] Use of "except Exception" vs. "except ... raise" in Python

查看:90
本文介绍了使用“例外除外”;与“除外...加薪”在Python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一些包含类似于以下功能的源代码:

I'm reading some source code which contains a function similar to the following:

def dummy_function():
    try:
        g = 1/0
    except Exception as e:
        raise Exception("There is an error: {}".format(e))

据我了解,所有异常均源自 Exception 类,因此这应该捕获所有错误。跟随 https://docs.python.org/3/tutorial/errors.html,那么,这是否不等于

As I understand it, all exceptions are derived from the Exception class, so this should catch all errors. Following https://docs.python.org/3/tutorial/errors.html, then, would this not be equivalent to

def dummy_function():
    try:
        g = 1/0
    except:
        print "There is an error:"
        raise

我注意到在任何一种情况下,打印输出的排列都略有不同,但是在我看来,第二种方法基本上是相同的,而且不太冗长。还是我错过了什么?

I notice that the printed output is arranged slightly differently in either case, but it would seem to me that the second method is basically the same and less verbose. Or am I missing something?

推荐答案

不,您的代码不相同,原因如下:

No, your code is not equivalent, for several reasons:


  • 空白除外:捕获所有异常,包括从 BaseException SystemExit KeyboardInterrupt GeneratorExit );捕获 Exception 会过滤掉您通常希望避免在不重新引发的情况下捕获的那些异常。在较早的Python版本中,它还会捕获字符串异常(不再允许)。

  • 异常除外,因为e 捕获子类,但是然后引发一个新的 Exception()实例;特定的类型信息不能在下游的 try ...中使用,除非语句。

  • 在Python 3中,产生了一个新的来自异常处理程序的异常会创建一个异常链(其中原始异常作为 Exception .__ context __ 属性添加,请参见 Python使用中的使用

  • 消息已更新;

  • A blank except: catches all exceptions, including those derived from BaseException (SystemExit, KeyboardInterrupt and GeneratorExit); catching Exception filters out those exceptions you generally want to avoid catching without a re-raise. In older Python releases, it would also catch string exceptions (no longer permitted).
  • The except Exception as e catches subclasses, but then raises a new Exception() instance; the specific type information can't be used anymore in downstream try...except statements.
  • In Python 3, raising a new exception from an exception handler creates an exception chain (where the original exception is added as the Exception.__context__ attribute, see Python "raise from" usage)
  • The message is updated; that's probably the whole point here, is to give the exception a different message.

您发现的代码是很不正确的做法。顶级异常处理程序应该只捕获并打印一条消息,也许还可以追溯一条消息,而不是使用新消息重新引发异常(并且在Python 2中丢失有关原始异常的所有信息,在Python 3中使其无法访问异常)匹配)。

The code you found is.. rather bad practice. The top-level exception handler should just catch and print a message and perhaps a traceback, rather than re-raise the exception with a new message (and in Python 2 lose all information on the original exception, in Python 3 make it inaccessible to exception matching in later handlers).

这篇关于使用“例外除外”;与“除外...加薪”在Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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