[英]Manually raising (throwing) an exception in Python
如何在 Python 中引发异常,以便以后可以通过except
块捕获它?
如何在 Python 中手动抛出/引发异常?
使用语义上适合您问题的最具体的 Exception 构造函数。
在您的信息中具体说明,例如:
raise ValueError('A very specific bad thing happened.')
避免引发泛型Exception
。 要捕获它,您必须捕获所有其他将其子类化的更具体的异常。
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
声明相反,请使用语义上适合您问题的最具体的 Exception 构造函数。
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 中,向BaseException
添加了一个实际的message
属性,以鼓励用户将 Exceptions 子类化并停止使用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]
如果你愿意,你可以修改你的新 raise 会发生什么 - 例如为实例设置新的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
我们在修改 args 时保留了整个回溯。 请注意,这不是最佳实践,并且在 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 中,您可以链接异常,以保留回溯:
raise RuntimeError('specific message') from error
意识到:
这些可以很容易地隐藏甚至进入生产代码。 您想引发异常,并且这样做会引发异常,但不是预期的!
在 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.')
不要这样做。 提出一个简单的
Exception
绝对不是正确的做法; 请参阅Aaron Hall 的出色答案。
没有比这更 Pythonic 的了:
raise Exception("I know Python!")
将Exception
替换为您要抛出的特定类型的异常。
如果您想了解更多信息,请参阅 Python 的 raise 语句文档。
在 Python 3 中有四种不同的引发异常的语法:
如果您使用raise exception (args)
来引发异常,则在您打印异常对象时将打印args
- 如下例所示。
# Raise exception (args)
try:
raise ValueError("I have raised an Exception")
except ValueError as exp:
print ("Error", exp) # Output -> Error I have raised an Exception
# Raise exception
try:
raise ValueError
except ValueError as exp:
print ("Error", exp) # Output -> Error
不带任何参数的raise
语句会重新引发最后一个异常。
如果您需要在捕获异常后执行一些操作然后想要重新引发它,这很有用。 但是如果之前没有任何异常, raise
语句会引发TypeError
异常。
def somefunction():
print("some cleaning")
a=10
b=0
result=None
try:
result=a/b
print(result)
except Exception: # Output ->
somefunction() # Some cleaning
raise # Traceback (most recent call last):
# File "python", line 8, in <module>
# ZeroDivisionError: division by zero
此语句用于创建异常链接,其中响应另一个异常而引发的异常可以包含原始异常的详细信息 - 如下例所示。
class MyCustomException(Exception):
pass
a=10
b=0
reuslt=None
try:
try:
result=a/b
except ZeroDivisionError as exp:
print("ZeroDivisionError -- ",exp)
raise MyCustomException("Zero Division ") from exp
except MyCustomException as exp:
print("MyException",exp)
print(exp.__cause__)
输出:
ZeroDivisionError -- division by zero
MyException Zero Division
division by zero
对于您需要抛出异常以响应某些意外情况的常见情况,并且您从不打算捕获,而只是快速失败以使您能够从那里进行调试,如果它发生了 - 最合乎逻辑的一个似乎是AssertionError
:
if 0 < distance <= RADIUS:
#Do something.
elif RADIUS < distance:
#Do something.
else:
raise AssertionError("Unexpected value of 'distance'!", distance)
首先阅读现有答案,这只是一个附录。
请注意,您可以使用或不使用参数引发异常。
例子:
raise SystemExit
退出程序,但您可能想知道发生了什么。 所以你可以使用这个。
raise SystemExit("program exited")
这将在关闭程序之前将“程序退出”打印到标准错误。
请注意:有时您确实想要处理通用异常。 如果您正在处理一堆文件并记录错误,您可能希望捕获文件发生的任何错误,记录它,然后继续处理其余文件。 在这种情况下,一个
try:
foo()
except Exception as e:
print(e) # Print out handled error
块是一个很好的方法。 不过,您仍然需要raise
特定的异常,以便了解它们的含义。
要捕获所有异常,请使用BaseException
。 它位于异常层次结构的顶部。
try:
# Do something
except BaseException as error:
print('An exception occurred: {}'.format(error))
try:
# Do something
except BaseException as error:
raise 'An exception occurred: {}'.format(error)
以上代码支持 Python 2.7 到最新版本。
参考: 异常层次结构
为此,您应该学习 Python 的raise语句。
它应该保存在 try 块内。
例子 -
try:
raise TypeError # Replace TypeError by any other error if you want
except TypeError:
print('TypeError raised')
您可能还想引发自定义异常。 例如,如果您正在编写一个库,那么为您的模块创建一个基本异常类,然后让自定义子异常更加具体,这是一个非常好的做法。
你可以这样实现:
class MyModuleBaseClass(Exception):
pass
class MoreSpecificException(MyModuleBaseClass):
pass
# To raise custom exceptions, you can just
# use the raise keyword
raise MoreSpecificException
raise MoreSpecificException('message')
如果您对自定义基类不感兴趣,您可以从普通异常类(如Exception
、 TypeError
、 ValueError
等)继承自定义异常类。
如果您不关心要引发哪个错误,则可以使用assert
引发AssertionError
:
>>> assert False, "Manually raised error"
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
assert False, "Manually raised error"
AssertionError: Manually raised error
>>>
如果条件为False
,则assert
关键字会引发AssertionError
。 在这种情况下,我们直接指定了False
,所以它会引发错误,但是要让它有一个我们希望它引发的文本,我们添加一个逗号并指定我们想要的错误文本。 在这种情况下,我写了Manually raised error
,并用该文本引发了它。
如果您不关心引发的异常,请执行以下操作:
def crash(): return 0/0
好旧的除以 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.