在python中立即重新引发并重新捕获错误
我在在python中立即重新引发并重新捕获错误,python,python-3.x,exception-handling,Python,Python 3.x,Exception Handling,我在python中有一些异常处理代码,其中可以引发两个异常,第一个异常是第二个异常的“超集” 也就是说,下面的代码总结了我需要做的事情(并且工作正常) 但它要求我将所有内容抽象为独立的函数,以便代码保持干净和可读性。我想要一些更简单的语法,比如: try: normal_execution_path() except FirstError: handle_first_error() raise SecondError except SecondError: han
python
中有一些异常处理代码,其中可以引发两个异常,第一个异常是第二个异常的“超集”
也就是说,下面的代码总结了我需要做的事情(并且工作正常)
但它要求我将所有内容抽象为独立的函数,以便代码保持干净和可读性。我想要一些更简单的语法,比如:
try:
normal_execution_path()
except FirstError:
handle_first_error()
raise SecondError
except SecondError:
handle_second_error()
但这似乎不起作用(
SecondError
如果在该块中引发,则不会被重新捕获)。但是,在这个方向上有什么可行的方法吗?如果希望手动抛出要处理的第二个错误,可以使用嵌套的try-catch块,如下所示:
try:
normal_execution_path()
except FirstError:
try:
handle_first_error()
raise SecondError
except SecondError:
handle_second_error()
except SecondError:
handle_second_error()
也许值得回顾一下代码体系结构。但对于你的特殊情况: 创建处理此类错误的泛型类。在第一个和第二个错误情况下从它继承。为此类错误创建处理程序。在处理程序中,检查第一个或第二个特殊情况,并使用瀑布进行处理
class SupersetException(Exception):
pass
class FirstError(SupersetException):
pass
class SecondError(SupersetException):
pass
def normal_execution_path():
raise SecondError
def handle_superset_ex(state):
# Our waterfall
# We determine from whom the moment to start processing the exception.
if type(state) is FirstError:
handle_first_error()
# If not the first, the handler above will be skipped
handle_second_error()
try:
normal_execution_path()
except SupersetException as state:
handle_superset_ex(state)
然后就开始构思吧。除非你指定一个额外的处理程序,否则你不能。如果错误是
FirstError
或SecondError
的实例,则在此处进行分支似乎更好。
class SupersetException(Exception):
pass
class FirstError(SupersetException):
pass
class SecondError(SupersetException):
pass
def normal_execution_path():
raise SecondError
def handle_superset_ex(state):
# Our waterfall
# We determine from whom the moment to start processing the exception.
if type(state) is FirstError:
handle_first_error()
# If not the first, the handler above will be skipped
handle_second_error()
try:
normal_execution_path()
except SupersetException as state:
handle_superset_ex(state)