[英]In python 3.6, how do I catch an exception and raise an exception to be handled later?
假設我有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)
而且,我有一個引發FooError
的函數:
def foobar (x):
if x < 0:
raise FooError()
通常,您可以使用try/except
塊來處理FooError
:
try:
foobar(-1)
except FooError:
print('Uh oh, foo error!')
sys.exit()
但是,我想拋出一個BarError
,以后可以處理。 像這樣:
except BarError:
print('Uh oh, bar error!')
sys.exit()
但是,在執行此操作時,我只是得到兩個錯誤的回溯:
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!
如何扔BarError
的處理程序的內部FooError
,然后處理BarError
在不同的except
塊?
不知道我是否理解您的要求,但是您可以在其他異常處理程序中輕松引發新的異常:
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")
您不必為此提供功能,也可以嵌套兩個try塊。
這回答了你的問題了嗎?
你不能 一旦捕獲到異常,就無法將控制權轉移到同一 try
語句中的except
block except
其他控件。 您可以使用嵌套語句:
try:
try:
foobar(-1)
except FooError:
raise BarError
except BarError:
print('Uh oh, bar error!')
sys.exit()
如果要區分之間的一些額外的工作是必要的BarError
小號直接提出foobar
和BarError
提出作為的結果FooError
被抓。 您可以為此使用異常鏈接。 有關更多詳細信息,請參見PEP-3134 。 這個例子可能不是寫這個的最好方法。
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")
聽起來您想捕獲FooError
或BarError
,但是如果它是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.