如何在Python中引发异常,以便以后可以通过except
块捕获它?
答案 0 :(得分:2395)
如何在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中,有利于鼓励用户子类化异常并停止使用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]
如果您愿意,可以修改新加注的内容 - 例如为实例设置新的参数:
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,就会警告消费者:
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.')
答案 1 :(得分:528)
不要这样做。提出一个裸
Exception
绝对是不正确的事情;请改为Aaron Hall's excellent answer。
无法获得比这更多的pythonic:
raise Exception("I know python!")
如果您想了解更多信息,请参阅the raise statement docs了解python。
答案 2 :(得分:32)
对于常见的情况,您需要抛出异常以响应某些意外情况,并且您永远不想捕获,但只是快速失败以使您能够从那里进行调试(如果它发生的话) - 最合乎逻辑的一个似乎是AssertionError
:
if 0 < distance <= RADIUS:
#Do something.
elif RADIUS < distance:
#Do something.
else:
raise AssertionError("Unexpected value of 'distance'!", distance)
答案 3 :(得分:30)
在Python3中,有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
答案 4 :(得分:10)
首先阅读现有答案,这只是一个附录。
请注意,您可以使用或不使用参数来引发异常。
示例:
raise SystemExit
退出程序,但你可能想知道发生了什么。所以你可以使用它。
raise SystemExit("program exited")
这将在关闭程序之前将“程序退出”打印到stderr。
答案 5 :(得分:0)
仅需注意:有时候您确实想处理通用异常。如果要处理大量文件并记录错误,则可能要捕获文件发生的任何错误,将其记录下来,然后继续处理其余文件。在这种情况下,try except Exception:
块是完成此操作的好方法。您仍然需要raise
特定异常,以便您了解异常的含义。
答案 6 :(得分:0)
引发异常的另一种方法是assert
。您可以使用assert来验证条件是否满足,否则将引发AssertionError
。有关更多详细信息,请查看here。
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))
答案 7 :(得分:0)
您应该为此学习python的凸起语句。 它应该保存在try块中。 示例-
try:
raise TypeError #remove TypeError by any other error if you want
except TypeError:
print('TypeError raised')
答案 8 :(得分:0)
您可能还想引发自定义异常。例如,如果您正在编写一个库,那么为您的模块创建一个基本异常类是一个非常好的做法,然后有更具体的自定义子异常。
你可以这样实现:
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
等)继承自定义异常类。