简体   繁体   English

在Python中的try catch块中根据条件调用不同的函数

[英]Call different function based on condition in try catch block in Python

I have a code where I am supposed to call different functions based on conditions. 我有一个代码,应该根据条件调用不同的函数。 Below is my code 下面是我的代码

try:
    if condition_1 is True:
        function1()
    if condition_2 is True:
        function2()
    if condition_3 is True:
        function3()

except Exception, e:
    raise e

There are cases when multiple conditions can be true. 在某些情况下可能满足多个条件。 So multiple function needs to be called and executed. 因此,需要调用和执行多个功能。 It worked fine until today when 1 of the function raised an exception. 直到今天,当函数1引发异常时,它运行良好。

condition_1 and condition_3 were true. condition_1condition_3为true。 So function1 and function3 were supposed to be executed. 因此,应该执行function1function3 When it called function1 , because of some error in function1 , it raised an exception, without executing function3 . 当所谓的function1 ,因为一些错误的, function1 ,它提出了一个异常,不执行function3 What I wanted, is that even if function1 raises error, it should still continue and check other conditions and execute respective functions accordingly. 我想要的是,即使function1出现错误,它也应该继续执行并检查其他条件并相应地执行相应的功能。

1 way to resolve this is to write each if condition in separate try/catch block. 解决此问题的一种方法是将每个if条件写入单独的try / catch块中。 But, is there a better way to resolve this? 但是,是否有更好的方法来解决此问题?

In my opinion, exceptions must be allowed to the interrupt the process if anything goes wrong in the way. 我认为,如果出现任何问题,则必须允许异常来中断该过程。 However, you can achieve this behavior by removing raise keyword. 但是,您可以通过删除raise关键字来实现此行为。

try:
    if condition_1 :
        function1()
    if condition_2 :
        function2()
    if condition_3 :
        function3()
except Exception, e:
    pass

Please take a look at Why is “except: pass” a bad programming practice? 请看看为什么“ except:pass”是一种不好的编程习惯?

PS: You do not need to check if True is True in conditions. PS:您不需要检查条件是否True is True

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

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