Aar*_*all 2685
如何在Python中手动抛出/引发异常?
使用最具体的Exception构造函数,它在语义上适合您的问题.
在您的消息中具体说明,例如:
raise ValueError('A very specific bad thing happened.')
Run Code Online (Sandbox Code Playgroud)
避免引发通用异常.为了捕获它,你必须捕获所有其他更具体的异常子类.
raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
Run Code Online (Sandbox Code Playgroud)
例如:
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',)
Run Code Online (Sandbox Code Playgroud)
更具体的捕获量不会捕获一般异常:
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
Run Code Online (Sandbox Code Playgroud)
raise
声明相反,请使用最具特异性的Exception构造函数,该构造函数在语义上适合您的问题.
raise ValueError('A very specific bad thing happened')
Run Code Online (Sandbox Code Playgroud)
它还可以方便地将任意数量的参数传递给构造函数:
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
Run Code Online (Sandbox Code Playgroud)
这些参数由args
Exception对象上的属性访问.例如:
try:
some_code_that_may_raise_our_value_error()
except ValueError as err:
print(err.args)
Run Code Online (Sandbox Code Playgroud)
版画
('message', 'foo', 'bar', 'baz')
Run Code Online (Sandbox Code Playgroud)
在Python 2.5中,实际message
属性被添加到BaseException中,有利于鼓励用户子类化Exceptions并停止使用args
,但args 的引入message
和原始弃用已被撤消.
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!
Run Code Online (Sandbox Code Playgroud)
您可以保留堆栈跟踪(和错误值)sys.exc_info()
,但这更容易出错并且在Python 2和3之间存在兼容性问题,更喜欢使用裸引导raise
来重新引发.
解释 - sys.exc_info()
返回类型,值和回溯.
type, value, traceback = sys.exc_info()
Run Code Online (Sandbox Code Playgroud)
这是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]
Run Code Online (Sandbox Code Playgroud)
如果您愿意,可以修改新加注的内容 - 例如为实例设置新的参数:
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
Run Code Online (Sandbox Code Playgroud)
我们在修改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>
Run Code Online (Sandbox Code Playgroud)
raise error.with_traceback(sys.exc_info()[2])
Run Code Online (Sandbox Code Playgroud)
再次:避免手动操纵回溯.这是效率较低,更容易出错.如果你正在使用线程,sys.exc_info
你甚至可能得到错误的回溯(特别是如果你使用异常处理控制流程 - 我个人倾向于避免.)
在Python 3中,您可以链接Exceptions,它可以保留回溯:
raise RuntimeError('specific message') from error
Run Code Online (Sandbox Code Playgroud)
意识到:
这些可以轻松隐藏甚至进入生产代码.你想引发一个异常,并且它们会引发异常,但不会引发异常!
在Python 2中有效,但在Python 3中没有以下内容:
raise ValueError, 'message' # Don't do this, it's deprecated!
Run Code Online (Sandbox Code Playgroud)
只有在旧版本的Python(2.4及更低版本)中有效,您仍然可以看到人们提升字符串:
raise 'message' # really really wrong. don't do this.
Run Code Online (Sandbox Code Playgroud)
在所有现代版本中,这实际上会引发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)))
Run Code Online (Sandbox Code Playgroud)
"我想故意制造一个错误,以便它会进入除外"
您可以创建自己的错误类型,如果要指示应用程序特定的错误,只需在异常层次结构中继承适当的点:
class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''
Run Code Online (Sandbox Code Playgroud)
和用法:
if important_key not in resource_dict and not ok_to_be_missing:
raise MyAppLookupError('resource is missing, and that is not ok.')
Run Code Online (Sandbox Code Playgroud)
Gab*_*ley 526
不要这样做.提出裸露
Exception
绝对不是正确的做法; 相反,请参阅Aaron Hall的优秀答案.
不能得到比这更多的pythonic:
raise Exception("I know python!")
Run Code Online (Sandbox Code Playgroud)
如果您想了解更多信息,请参阅python 的raise语句文档.
N R*_*awa 44
在Python3中,有4种不同的语法用于rasing异常:
1. raise exception
2. raise exception (args)
3. raise
4. raise exception (args) from original_exception
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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__)
Run Code Online (Sandbox Code Playgroud)
输出:
ZeroDivisionError -- division by zero
MyException Zero Division
division by zero
Run Code Online (Sandbox Code Playgroud)
Evg*_*eev 33
对于常见的情况,您需要抛出异常以响应某些意外情况,并且您永远不想捕获,但只是快速失败以使您能够从那里进行调试(如果它发生的话) - 最合乎逻辑的一个似乎是AssertionError
:
if 0 < distance <= RADIUS:
#Do something.
elif RADIUS < distance:
#Do something.
else:
raise AssertionError("Unexpected value of 'distance'!", distance)
Run Code Online (Sandbox Code Playgroud)
Ana*_*ash 11
首先阅读现有的答案,这只是一个附录.
请注意,您可以使用或不使用参数引发异常.
例:
raise SystemExit
Run Code Online (Sandbox Code Playgroud)
退出程序,但你可能想知道发生了什么.所以你可以使用它.
raise SystemExit("program exited")
Run Code Online (Sandbox Code Playgroud)
这将在关闭程序之前将"程序退出"打印到stderr.
请注意:有时您确实希望处理通用异常。如果您正在处理一堆文件并记录错误,您可能希望捕获文件发生的任何错误,记录它,然后继续处理其余文件。在这种情况下,一个
try:
foo()
except Exception as e:
print(e) # Print out handled error
Run Code Online (Sandbox Code Playgroud)
块是一个很好的方法来做到这一点。不过,您仍然需要raise
特定的例外情况,以便了解它们的含义。
另一种抛出异常的方法是assert
. 您可以使用 assert 来验证是否满足条件,否则它将引发AssertionError
。有关更多详细信息,请查看此处。
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
Run Code Online (Sandbox Code Playgroud)