【问题标题】:Raising exception from within except clause从 except 子句中引发异常
【发布时间】:2016-09-10 20:09:12
【问题描述】:

我想知道我们是否可以执行以下操作:
我们捕获套接字错误,如果消息与某个值不同,
将异常向前提出以在下面的下一个一般除外子句中捕获?

try:
    some logic to connect to a server..   

except socket.error as se:
    if se.messsage != '123':
       raise Exception(se.message)
except exception as ex:
    log.error('write something')

【问题讨论】:

  • 不,你不能。但是您可以将try...except 嵌套在另一个try...except 中。
  • 我也想过,但是外观和感觉都不好

标签: python exception-handling


【解决方案1】:

为此,您需要一组 try-catch 块。一旦捕获到异常,重新抛出异常会导致它在外部级别被捕获。在块内尝试 if else 或简单地将 try-except 块嵌套在另一个块中,如下所示:

try:
    try:
        #...
    except:
        raise
except:
    pass

【讨论】:

  • 我将其称为“嵌套的 try-except 块”并编写示例以更紧密地匹配问题,但其他方面的答案很好。
【解决方案2】:

您可以简单地使用raise 重新引发异常,无需参数:

try:
    # some code
except:
    if condition:
        raise

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多