如何在Python中引发异常,以便以后可以通过except
块捕获?
如何在Python中手动抛出/引发异常?
Use the most specific Exception constructor that semantically fits your issue。
在您的信息中具体说明,例如:
raise ValueError('A very specific bad thing happened.')
避免引发通用异常。为了捕获它,你必须捕获所有其他更具体的异常子类。
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
声明Instead, use the most specific Exception constructor that semantically fits your issue。
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中,有利于鼓励用户子类化Exceptions并停止使用args
,但the introduction of message
and the original deprecation of args has been retracted。
except
条款例如,在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] + ' <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])
再次:避免手动操纵回溯。这是less efficient,更容易出错。如果你正在使用线程和sys.exc_info
,你甚至可能得到错误的回溯(特别是如果你使用异常处理控制流 - 我个人倾向于避免。)
在Python 3中,您可以链接Exceptions,它可以保留回溯:
raise RuntimeError('specific message') from error
意识到:
这些可以轻松隐藏甚至进入生产代码。你想引发一个异常,并且它们会引发异常,但不会引发异常!
Valid in Python 2, but not in Python 3如下:
raise ValueError, 'message' # Don't do this, it's deprecated!
只有valid in much older versions of Python(2.4及更低),你仍然可以看到人们提高字符串:
raise 'message' # really really wrong. don't do this.
在所有现代版本中,这实际上会引发TypeError,因为您没有引发BaseException类型。如果您没有检查正确的例外情况并且没有知道该问题的审阅者,那么它可能会投入生产。
如果他们错误地使用了我的API,我会引发Exceptions警告消费者:
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's excellent answer。
不能得到比这更多的pythonic:
raise Exception("I know python!")
如果您想了解更多信息,请参阅the raise statement docs for python。
在Python 3中,有4种不同的语法用于引发异常:
1. raise exception
2. raise exception (args)
3. raise
4. raise exception (args) from original_exception
1.引发异常与2.引发异常(args)
如果使用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 execption
try:
raise ValueError
except ValueError as exp:
print ("Error", exp) # Output -> Error
3.raise
没有任何参数的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
4.从original_exception中引发异常(args)
此语句用于创建异常链接,其中为响应另一个异常而引发的异常可以包含原始异常的详细信息 - 如下面的示例所示。
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")
这将在关闭程序之前将“程序退出”打印到stderr。
需要注意的是:有时候你想要处理一般异常。如果您正在处理大量文件并记录错误,您可能希望捕获文件发生的任何错误,记录并继续处理其余文件。在这种情况下,try except Exception:
阻止了一个很好的方法。你仍然想要raise
特定的异常,所以你知道它们的含义。