如何在Python中手动抛出/引发异常?
使用最具特异性的Exception构造函数,该构造函数在语义上适合您的问题。
在您的信息中具体说明,例如:
raise ValueError('A very specific bad thing happened.')
不要引发一般异常
避免引发通用异常。 为了捕获它,您将必须捕获所有其他更具体的异常子类。
问题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',)
问题2:不会抓住
更具体的捕获量不会捕获一般异常:
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 "", line 1, in
File "", line 3, in demo_no_catch
Exception: general exceptions not caught by specific handling
最佳实践:sys.exc_info声明
相反,使用最具特异性的Exception构造函数,它在语义上适合您的问题。
raise ValueError('A very specific bad thing happened')
它还可以方便地将任意数量的参数传递给构造函数:
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
这些参数由Exception对象上的sys.exc_info属性访问。 例如:
try:
some_code_that_may_raise_our_value_error()
except ValueError as err:
print(err.args)
版画
('message', 'foo', 'bar', 'baz')
在Python 2.5中,实际的sys.exc_info属性被添加到BaseException,有利于鼓励用户子类化Exceptions并停止使用raise,但是引入了sys.exc_info并且args的原始弃用已被撤消。
最佳实践:sys.exc_info子句
例如,在except子句中,您可能希望记录发生特定类型的错误,然后重新引发。 在保留堆栈跟踪的同时执行此操作的最佳方法是使用bare 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]
如果您愿意,可以修改新加注的情况 - 例如 为实例设置新的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] + ' ',)
raise error_type, error_instance, traceback
我们在修改args时保留了整个回溯。 请注意,这不是最佳实践,它在Python 3中是无效的语法(使兼容性更难以解决)。
>>> catch_error_modify_message()
Traceback (most recent call last):
File "", line 1, in
File "", line 3, in catch_error_modify_message
File "", line 2, in error
ValueError: oops!
在Python 3中:
raise error.with_traceback(sys.exc_info()[2])
再次:避免手动操纵回溯。 它效率低,容易出错。 如果您正在使用线程和sys.exc_info,您甚至可能会得到错误的回溯(特别是如果您正在使用控制流的异常处理 - 我个人倾向于避免这种情况。)
Python 3,异常链接
在Python 3中,您可以链接Exceptions,它可以保留回溯:
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,我会提出异常以警告消费者我的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)))
在apropos时创建自己的错误类型
“我想故意犯错误,以便它会进入除外”
您可以创建自己的错误类型,如果要指示应用程序的特定错误,只需将异常层次结构中的相应点子类化:
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.')