[英]In python 3.6, how do I catch an exception and raise an exception to be handled later?
Suppose I have 2 exceptions: 假设我有2个例外:
class FooError (Exception):
def __init__(self, *args, **kwargs):
default_message = 'A foo error has occurred!'
if not (args or kwargs): args = (default_message,)
super().__init__(*args, **kwargs)
class BarError (Exception):
def __init__(self, *args, **kwargs):
default_message = 'A bar error has occurred!'
if not (args or kwargs): args = (default_message,)
super().__init__(*args, **kwargs)
And, I have a function which throws FooError
: 而且,我有一个引发FooError
的函数:
def foobar (x):
if x < 0:
raise FooError()
Generally, you would handle FooError
with a try/except
block: 通常,您可以使用try/except
块来处理FooError
:
try:
foobar(-1)
except FooError:
print('Uh oh, foo error!')
sys.exit()
However, I would like to throw a BarError
which I can handle later. 但是,我想抛出一个BarError
,以后可以处理。 Something like this: 像这样:
except BarError:
print('Uh oh, bar error!')
sys.exit()
When executing this, though, I just get the traceback of both errors: 但是,在执行此操作时,我只是得到两个错误的回溯:
Traceback (most recent call last):
File "C:\Users\Maze\Desktop\test2.py", line 17, in <module>
foobar(-1)
File "C:\Users\Maze\Desktop\test2.py", line 15, in foobar
raise FooError()
__main__.FooError: A foo error has occurred!
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Maze\Desktop\test2.py", line 19, in <module>
raise BarError()
__main__.BarError: A bar error has occurred!
How do I throw BarError
inside of the handler for FooError
, and then handle BarError
in a different except
block? 如何扔BarError
的处理程序的内部FooError
,然后处理BarError
在不同的except
块?
Not sure whether I understood what you were asking, but you can easily raise new exceptions in other exception handlers: 不知道我是否理解您的要求,但是您可以在其他异常处理程序中轻松引发新的异常:
def call_foobar():
try:
foobar(-1)
except FooError:
print('Uh oh, foo error!')
raise BarError()
try:
call_foobar()
except BarError as e:
print("Bar Error")
You don't necessarily need a function for this, nesting two try blocks would be possible as well. 您不必为此提供功能,也可以嵌套两个try块。
Does this answer your question? 这回答了你的问题了吗?
You can't. 你不能 Once you've caught an exception, you can't transfer control to another except
block in the same try
statement. 一旦捕获到异常,就无法将控制权转移到同一 try
语句中的except
block except
其他控件。 You can use a nested statement: 您可以使用嵌套语句:
try:
try:
foobar(-1)
except FooError:
raise BarError
except BarError:
print('Uh oh, bar error!')
sys.exit()
Some additional work is necessary if you want to distinguish between BarError
s raised directly by foobar
and the BarError
raised as a result of the FooError
being caught. 如果要区分之间的一些额外的工作是必要的BarError
小号直接提出foobar
和BarError
提出作为的结果FooError
被抓。 You can use exception chaining for this. 您可以为此使用异常链接。 See PEP-3134 for more details; 有关更多详细信息,请参见PEP-3134 。 this example may not be the best way to write this. 这个例子可能不是写这个的最好方法。
try:
try:
foobar(-1)
except FooError as exc:
raise BarError from exc
except BarError as exc:
if isinstance(exc.__cause__, FooError):
print("Caught a Foo-induced BarError")
else:
print("Caught a regular BarError")
It sounds like you want to catch a FooError
or BarError
, but you want to do a little extra work first if it is a FooError
. 听起来您想捕获FooError
或BarError
,但是如果它是FooError
一些额外的工作。 If that's the case, you can catch both kinds of exception and only do the work for a FooError
: 在这种情况下,您可以捕获两种异常,并且只能针对FooError
进行工作:
try:
foobar(-1)
except (FooError, BarError) as e:
if isinstance(e, FooError):
# do extra work
# Handle errors
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.