在 Python 中手动引发(抛出)异常

新手上路,请多包涵

我如何在 Python 中引发异常以便稍后可以通过 except 块捕获?

原文由 TIMEX 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 351
2 个回答

如何在 Python 中手动抛出/引发异常?

使用语义上适合您的问题的最具体的异常构造函数

在您的消息中具体说明,例如:

 raise ValueError('A very specific bad thing happened.')

不要引发一般异常

避免提出通用的 Exception 。要捕获它,您必须捕获所有其他将它子类化的更具体的异常。

问题 1:隐藏错误

raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.

例如:

 def demo_bad_catch():
    try:
        raise ValueError('Represents a hidden bug, do not catch this')
        raise Exception('This is the exception you expect to handle')
    except Exception as error:
        print('Caught this error: ' + repr(error))

>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug, do not catch this',)

问题二:抓不住

更具体的捕获不会捕获一般异常:

 def demo_no_catch():
    try:
        raise Exception('general exceptions not caught by specific handling')
    except ValueError as e:
        print('we will not catch exception: Exception')


>>> demo_no_catch()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling

最佳实践: raise 声明

相反,使用语义上适合您的问题的最具体的异常构造函数

 raise ValueError('A very specific bad thing happened')

这也方便地允许将任意数量的参数传递给构造函数:

 raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')

这些参数由 Exception args 属性访问。例如:

 try:
    some_code_that_may_raise_our_value_error()
except ValueError as err:
    print(err.args)

印刷

('message', 'foo', 'bar', 'baz')

在 Python 2.5 中,一个实际的 message 属性被添加到 BaseException 以鼓励用户子类化异常并停止使用 args message args 的原始弃用已被收回

最佳实践: except 条款

例如,在 except 子句中时,您可能想要记录发生的特定类型的错误,然后重新引发。在保留堆栈跟踪的同时执行此操作的最佳方法是使用裸 raise 语句。例如:

 logger = logging.getLogger(__name__)

try:
    do_something_in_app_that_breaks_easily()
except AppError as error:
    logger.error(error)
    raise                 # just this!
    # raise AppError      # Don't do this, you'll lose the stack trace!

不要修改你的错误……但如果你坚持。

您可以使用 sys.exc_info() 保留堆栈跟踪(和错误值),但这 更容易出错 并且 在 Python 2 和 3 之间存在兼容性问题,更喜欢使用裸 raise 来重新-增加。

解释一下 sys.exc_info() 返回类型、值和回溯。

 type, value, traceback = sys.exc_info()

这是 Python 2 中的语法——注意这与 Python 3 不兼容:

 raise AppError, error, sys.exc_info()[2] # avoid this.
# Equivalently, as error *is* the second object:
raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]

如果你愿意,你可以修改你的新加薪会发生什么 - 例如设置 new args 例如:

 def error():
    raise ValueError('oops!')

def catch_error_modify_message():
    try:
        error()
    except ValueError:
        error_type, error_instance, traceback = sys.exc_info()
        error_instance.args = (error_instance.args[0] + ' <modification>',)
        raise error_type, error_instance, traceback

我们在修改参数时保留了整个回溯。请注意,这 不是最佳实践,它在 Python 3 中是 无效语法(使得保持兼容性更难解决)。

 >>> catch_error_modify_message()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in catch_error_modify_message
  File "<stdin>", line 2, in error
ValueError: oops! <modification>

Python 3 中:

 raise error.with_traceback(sys.exc_info()[2])

再次重申:避免手动操作回溯。它 效率较低 且更容易出错。如果您使用线程和 sys.exc_info 您甚至可能得到错误的回溯(特别是如果您使用异常处理来控制流——我个人倾向于避免这种情况。)

Python 3,异常链

在 Python 3 中,您可以链接异常,从而保留回溯:

 raise RuntimeError('specific message') from error

意识到:

  • 确实 允许更改引发的错误类型,并且
  • 这与 Python 2 兼容。

弃用的方法:

这些可以很容易地隐藏甚至进入生产代码。您想引发异常,而这样做会引发异常, 但不是预期的异常!

以下内容 在 Python 2 中有效,但在 Python 3 中无效:

 raise ValueError, 'message' # Don't do this, it's deprecated!

在更旧版本的 Python (2.4 及更低版本)中有效,您可能仍会看到人们提出字符串:

 raise 'message' # really really wrong. don't do this.

在所有现代版本中,这实际上会引发 TypeError ,因为您没有引发 BaseException 类型。如果您没有检查正确的异常并且没有了解该问题的审阅者,它可能会投入生产。

用法示例

如果消费者使用我的 API 不正确,我会引发异常以警告他们:

 def api_func(foo):
    '''foo should be either 'baz' or 'bar'. returns something very useful.'''
    if foo not in _ALLOWED_ARGS:
        raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))

适当时创建自己的错误类型

“我想故意犯错误,这样它就会进入例外”

你可以创建自己的错误类型,如果你想指出你的应用程序有什么特定的错误,只需在异常层次结构中子类化适当的点:

 class MyAppLookupError(LookupError):
    '''raise this when there's a lookup error for my app'''

和用法:

 if important_key not in resource_dict and not ok_to_be_missing:
    raise MyAppLookupError('resource is missing, and that is not ok.')

原文由 Russia Must Remove Putin 发布,翻译遵循 CC BY-SA 4.0 许可协议

_不要这样做_。养一个裸体 Exception 绝对 不是 正确的做法;请参阅 Aaron Hall 的出色回答

没有比这更 Pythonic 的了:

 raise Exception("I know Python!")

Exception 替换为您要抛出的特定异常类型。

如果您需要更多信息,请参阅 Python 的 raise 语句文档

原文由 Gabriel Hurley 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题