繁体   English   中英

使用try除外块的更好方法

[英]Better way to use try except block

我有一个执行多个Python语句的要求,即使执行失败,我也很少希望执行其余的语句。

目前,我正在做:

try:
    wx.StaticBox.Destroy()
    wx.CheckBox.Disable()
    wx.RadioButton.Enable()
except:
    pass

如果任何一条语句失败,则将执行except ,程序退出。 但是我需要的是即使失败,它也应该运行所有三个语句。

如何在Python中执行此操作?

在要调用的方法上使用for循环,例如:

for f in (wx.StaticBox.Destroy, wx.CheckBox.Disable, wx.RadioButton.Enable):
    try:
        f()
    except Exception:
        pass

请注意,此处我们使用的是except Exception ,这通常比您想要的except更可能。

如果在try块期间发生异常,则跳过该块的其余部分。 您应该为三个单独的语句使用三个单独的try子句。

添加以回应评论:

由于您显然想处理许多语句,因此可以使用包装器方法检查异常:

def mytry(functionname):
    try:
        functionname()
    except Exception:
        pass

然后以您的函数名称作为输入来调用该方法:

mytry(wx.StaticBox.Destroy)

我建议创建一个上下文管理器类,该类禁止任何异常以及要记录的异常。

请查看下面的代码。 将鼓励对此进行任何改进。

import sys
class catch_exception:
    def __init__(self, raising=True):
        self.raising = raising

    def __enter__(self):
        pass

    def __exit__(self, type, value, traceback):
        if issubclass(type, Exception):
            self.raising = False

        print ("Type: ", type, " Log me to error log file")
        return not self.raising



def staticBox_destroy():
    print("staticBox_destroy")
    raise TypeError("Passing through")

def checkbox_disable():
    print("checkbox_disable")
    raise ValueError("Passing through")

def radioButton_enable():
    print("radioButton_enable")
    raise ValueError("Passing through")


if __name__ == "__main__":
    with catch_exception() as cm:
        staticBox_destroy()
    with catch_exception() as cm:
        checkbox_disable()
    with catch_exception() as cm:
        radioButton_enable()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM