【问题标题】:Avoid nested try/except避免嵌套的 try/except
【发布时间】:2020-11-26 17:46:43
【问题描述】:

我的代码结构如下:

try:
    x = function_one(args)
    try:
        y = function_two(args)
        try:
            #
            # some code where I need x and y
            #
        except Exception as e::
            print("Problem with code above : ", e)
    except Exception as e:
        print("Problem with function_two : ", e)
    #
    # some code here
    #
except Exception as e:
        print("Problem with function_one : ", e)

它有效,但我想知道我是否可以避免这种嵌套的尝试/异常? 例如,如果 x 为空并且之后不能使用,最好将 try / except 放在 function_one 中并找到一个解决方案来检查我是否可以将 x 用于其余代码,如果不能,则停止代码 ? 我可以做一个if x something,但它也会创建嵌套部分。

【问题讨论】:

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


    【解决方案1】:

    如果您只使用 try\except 检查某个代码块,您可以将该代码块包装在处理程序中:

    try:
        x = function_one(args)
    except Exception as e:
            print("Problem with function_one : ", e)   
             
    try:
        y = function_two(args)
    except Exception as e:
       print("Problem with function_two : ", e)
       
    try:
        #
        # some code where I need x and y
        #
    except Exception as e::
        print("Problem with code above : ", e)
        
    try:
        #
        # some code here
        #
    except Exception as e::
        print("Problem with code above : ", e)
    

    一般来说,如果您打算在内部块中处理更具体的错误,则只嵌套异常块。

    【讨论】:

    • 这个问题是,如果我在第一个有错误,我将在第三个区块中至少有一个错误,如果我在第一个之后停止,我可以避免
    【解决方案2】:

    如果您的异常块没有执行某些功能(如果内部甚至有错误,则继续执行其余代码),则不应使用嵌套的 try-catch 块。相反,您可以编写更多异常块。例如,

    try:
        x = function_one(args)
        
        y = function_two(args)
            
    except Exceptionx as e:
            print("Problem with function_one : ", e)
    except Exceptiony as e:
            print("Problem with function_two : ", e)
    

    ExceptionxExceptiony应该是Exception类对象,你应该知道你会得到什么样的异常。您可以在以下位置了解更多示例 https://docs.python.org/3/tutorial/errors.html

    【讨论】:

    • 我想我会这样做,但要添加一个一般性,除了@Tomer Yogev 所说的回溯,因为我不知道它会创建哪种异常
    【解决方案3】:

    如果不同 except 块的原因是为了更好地了解错误发生的位置,您可以将整个块包装在单个 try-except 块中并打印回溯:

    import traceback
    
    try:
        x = function_one(args)
        y = function_two(args)
    except:
        traceback.print_exc()
    

    【讨论】:

      猜你喜欢
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 2013-11-21
      • 1970-01-01
      • 2013-09-01
      • 2011-12-09
      • 2020-08-30
      • 1970-01-01
      相关资源
      最近更新 更多