简体   繁体   English

在python中,有没有办法在满足条件时进入try/except块,否则直接执行try块中的代码?

[英]In python, is there a way to enter a try/except block if a condition is met, otherwise execute the code in the try block plainly?

I would like to execute a loop that attempts to run a block of code, and skips past any iterations that happen to fail.我想执行一个尝试运行代码块的循环,并跳过任何碰巧失败的迭代。 However I would also like to be able to pass in a debug flag, so that if one of the iterations fails the program crashes and the user can see the backtrace to help themselves see where it failed.但是,我也希望能够传入一个调试标志,这样如果其中一个迭代失败,程序就会崩溃,用户可以查看回溯以帮助自己查看失败的位置。 Essentially, I want to do this:基本上,我想这样做:

debug = False  # or True
for i in range(10):
    if not debug:
        try:
            # many lines of code
        except:
            print(f'Case {i} failed')
    else:
        # many lines of code

However, I don't want to duplicate the #many lines of code .但是,我不想重复#many lines of code I could wrap them in a helper function and do precisely the structure I wrote above, but I'm going to have to pass around a bunch of variables that will add some complexity (aka unit tests that I don't want to write).我可以将它们包装在一个辅助函数中并精确地执行我上面写的结构,但是我将不得不传递一堆会增加一些复杂性的变量(也就是我不想编写的单元测试)。 Is there another way to do this?有没有另一种方法可以做到这一点?

Best solution shy of factoring out many lines of code to its own function (which is often a good idea, but not always) would be to unconditionally use the try / except , but have the except conditionally re-raise the exception:避免将many lines of code分解为自己的函数(这通常是一个好主意,但并非总是如此)的最佳解决方案是无条件使用try / except ,但让except有条件地重新引发异常:

debug = False  # or True
for i in range(10):
    try:
        # many lines of code
    except:
        if debug:
            raise  # Bare raise reraises the exception as if it was never caught
        print(f'Case {i} failed')

A caught exception reraised with a bare raise leaves no user-visible traces to distinguish it from an uncaught exception;一个捕获的异常被一个空的raise没有留下用户可见的痕迹来区分它与未捕获的异常; the traceback is unchanged, with no indication of it passing through the except block, so the net effect is identical to your original code, aside from debug being evaluated later (not at all if no exception occurs) and many lines of code appearing only once.回溯没有变化,没有任何迹象表明它通过了except块,因此净效果与您的原始代码相同,除了稍后评估debug (如果没有异常发生,则根本不会)和many lines of code只出现一次.

Side-note: Bare except blocks are a bad idea.旁注: exceptexcept裸露是一个坏主意。 If nothing else, limit it to except Exception: so you're not catching and suppressing stuff like KeyboardInterrupt or SystemExit when not in debug mode.如果不出意外,请将其限制为except Exception:这样您就不会在非调试模式下捕获和抑制诸如KeyboardInterruptSystemExit类的东西。

Best way is to use a function, just one line more does not matter too much.最好的方法是使用一个函数,多一行也无所谓。

Otherwise, if there is no need to test debug , There is no need to repeat the else block.否则,如果不需要测试debug ,则不需要重复else块。 Because if statements in try don't raise error, then the it will execute and result will be shown normally.因为如果try语句不会引发错误,那么它将执行并且结果将正常显示。

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

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