【问题标题】:Re-raise and re-catch error immediately in python在 python 中立即重新引发并重新捕获错误
【发布时间】:2017-06-25 11:51:31
【问题描述】:

我在python 中有一些异常处理代码,其中可以引发两个异常,第一个是第二个的“超集”。

即以下代码总结了我需要做的事情(并且工作正常)

try:
    normal_execution_path()
except FirstError:
    handle_first_error()
    handle_second_error()
except SecondError:
    handle_second_error()

但这需要我将所有内容抽象为独立的函数,以使代码保持干净和可读。我正在寻找一些更简单的语法,例如:

try:
    normal_execution_path()
except FirstError:
    handle_first_error()
    raise SecondError
except SecondError:
    handle_second_error()

但这似乎不起作用(SecondError 如果在此块内引发,则不会被重新捕获)。不过在这个方向有什么可行的吗?

【问题讨论】:

  • 你不能,除非你指定一个额外的处理程序。如果错误是FirstErrorSecondError 的实例,则在此处进行分支似乎更好。

标签: python python-3.x exception-handling


【解决方案1】:

如果您希望手动抛出要处理的第二个错误,您可以使用嵌套的 try-catch 块,如下所示:

try:
    normal_execution_path()
except FirstError:
    try:
        handle_first_error()
        raise SecondError
    except SecondError:
        handle_second_error()
except SecondError:
        handle_second_error()

【讨论】:

    【解决方案2】:

    也许值得回顾一下代码架构。但对于您的特殊情况:

    创建一个处理此类错误的通用类。从它继承第一个和第二个错误情况。为此类错误创建一个处理程序。在处理程序中,检查第一个或第二个特殊情况并使用瀑布进行处理。

    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)
    

    然后就发展这个想法。

    【讨论】:

      猜你喜欢
      • 2011-09-12
      • 2020-10-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2017-07-24
      • 2015-04-25
      • 2018-12-14
      • 2018-12-04
      相关资源
      最近更新 更多