简体   繁体   中英

Better way to use try except block

I have a requirement to execute multiple Python statements and few of them might fail during execution, even after failing I want the rest of them to be executed.

Currently, I am doing:

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

If any one of the statements fails, except will get executed and program exits. But what I need is even though it is failed it should run all three statements.

How can I do this in Python?

Use a for loop over the methods you wish to call, eg:

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

Note that we're using except Exception here - that's generally much more likely what you want than a bare except.

If an exception occurs during a try block, the rest of the block is skipped. You should use three separate try clauses for your three separate statements.

Added in response to comment:

Since you apparently want to handle many statements, you could use a wrapper method to check for exceptions:

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

Then call the method with the name of your function as input:

mytry(wx.StaticBox.Destroy)

I would recommend creating a context manager class that suppress any exception and the exceptions to be logged.

Please look at the code below. Would encourage any improvement to it.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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