简体   繁体   English

在 if-else 块中使用 try-except

[英]Using try-except in an if-else block

I'm trying to do the following in Python 2.7:我正在尝试在 Python 2.7 中执行以下操作:

if condition_a:
    try:
        b = func_1()
    except:
        b = func_2()
else:
    b = func_2()

Is there a better way to write this that avoids having the line b = func_2() twice?有没有更好的方法来写这个以避免行b = func_2()两次? I want to try and say, if an exception is raised in the try block, we should move to the logic in the else block.我想尝试说,如果在 try 块中引发异常,我们应该转移到 else 块中的逻辑。

Not the code I am the proudest of, but without more context, I can't think of anything cleaner:不是我最引以为豪的代码,但没有更多的上下文,我想不出任何更简洁的东西:

is_b_set = False

if condition_a:
   try:
       b = func_1()
       is_b_set = True
   except:
       # handle/log exception properly
       pass 

b = func_2() if not is_b_set else b

Not really, no.不是真的,不是。

An exception can't be tested for ahead of time (well, it could if you can check the underlying reasons for it in advance, but let's assume you can't here).无法提前测试异常(好吧,如果您可以提前检查其根本原因,则可以,但我们假设您不能在这里)。 So you have to do it.所以你必须这样做。

It will have to be nested somewhere under an if/else construct and will end up looking much like your example.它必须嵌套在if/else结构下的某处,最终看起来很像您的示例。

To me at least, both answers given so far are quite a bit less clear in their intent than your code.至少对我来说,到目前为止给出的两个答案的意图都比您的代码要不清楚。 I'd have to stop and think a bit about what the code execution flow is likely to do under various conditions and why the code was structured that way.我不得不停下来思考一下代码执行流程在各种条件下可能会做什么,以及为什么代码是这样构建的。

Don't repeat yourself is important - duplicated code is a code smell, often.不要重复自己很重要 - 重复的代码通常是一种代码味道。 But simplicity and obviousness has a virtue all of its own.但是简单和显而易见有其自身的优点。

Zen of Python quotes : Python 之禅名言

Simple is better than complex.简单胜于复杂。 Readability counts.可读性很重要。 Errors should never pass silently.🎗错误不应该默默地传递。🎗

Now, maybe you are not telling us the whole story and you have 20 branches of if-elif-elif-elif....else .现在,也许你没有告诉我们整个故事,你有 20 个if-elif-elif-elif....else分支。 Or maybe it's not really b = func_2() but 20 lines of duplicated code.或者也许它不是真正的b = func_2()而是 20 行重复的代码。

Post that code then, people can often replace big choices like that with dictionaries or maybe the duplicated code can be moved to another function.然后发布该代码,人们通常可以用字典替换诸如此类的大选择,或者可以将重复的代码移动到另一个函数中。

But regarding your original question, I think the best is leave-as-is.但关于你最初的问题,我认为最好的是保持原样。

🎗 Now, I know yours is sample code, but there is one thing I would change: 🎗 现在,我知道您的代码是示例代码,但我要更改一件事:


    try:
        b = func_1()
    except (<your expected exception>,):
        b = func_2()

Having a bare except : that then suppresses the exception is a massive swamp waiting to drag you down at the first opportunity in Python.有一个空的except :然后抑制异常是一个巨大的沼泽,等待在 Python 中一有机会就拖累你。 It will bite you.咬你。 Only do it trivial things like maybe a non-essential decorating an exception message in code - if that doesn't work - just skip adding the extra info.只做一些微不足道的事情,比如在代码中装饰一个非必要的异常消息 - 如果这不起作用 - 只需跳过添加额外信息。

You could use assertion.你可以使用断言。

try:
    assert condition_a
    func_1()
except:
    func_2()

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

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