[英]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. 我有一个执行多个Python语句的要求,即使执行失败,我也很少希望执行其余的语句。
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. 如果任何一条语句失败,则将执行
except
,程序退出。 But what I need is even though it is failed it should run all three statements. 但是我需要的是即使失败,它也应该运行所有三个语句。
How can I do this in Python? 如何在Python中执行此操作?
Use a for
loop over the methods you wish to call, eg: 在要调用的方法上使用
for
循环,例如:
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. 请注意,此处我们使用的是
except Exception
,这通常比您想要的except更可能。
If an exception occurs during a try
block, the rest of the block is skipped. 如果在
try
块期间发生异常,则跳过该块的其余部分。 You should use three separate try
clauses for your three separate statements. 您应该为三个单独的语句使用三个单独的
try
子句。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.