首页 > 解决方案 > 避免嵌套的 try/except

问题描述

我有以下代码结构:

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,但它也会创建嵌套部分。

标签: pythonpython-3.xerror-handling

解决方案


如果您只使用 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)

通常,如果您打算在内部块中处理更具体的错误,则仅嵌套异常块。


推荐阅读