python捕获异常并继续尝试块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19522990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:57:30  来源:igfitidea点击:

python catch exception and continue try block

pythonexception

提问by igor

Can I return to executing try-block after exception occurs? (The goal is to write less) For Example:

异常发生后我可以返回执行try-block吗?(目标是少写)例如:

try:
    do_smth1()
except:
    pass

try:
    do_smth2()
except:
    pass

vs

对比

try:
    do_smth1()
    do_smth2()
except:
    ??? # magic word to proceed to do_smth2() if there was exception in do_smth1

采纳答案by igor

No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.

不,你不能那样做。这就是 Python 的语法方式。一旦由于异常退出 try 块,就无法返回。

What about a for-loop though?

但是 for 循环呢?

funcs = do_smth1, do_smth2

for func in funcs:
    try:
        func()
    except Exception:
        pass  # or you could use 'continue'

Note however that it is considered a bad practice to have a bare except. You should catch for a specific exception instead. I captured for Exceptionbecause that's as good as I can do without knowing what exceptions the methods might throw.

但是请注意,使用裸except. 您应该改为捕获特定的异常。我Exception之所以捕获它,是因为在不知道这些方法可能会抛出哪些异常的情况下,我可以做到这一点。

回答by David Neale

You could iterate through your methods...

你可以遍历你的方法......

for m in [do_smth1, do_smth2]:
    try:
        m()
    except:
        pass

回答by rlms

I don't think you want to do this. The correct way to use a trystatement in general is as precisely as possible. I think it would be better to do:

我认为你不想这样做。try一般来说,使用语句的正确方法是尽可能精确。我认为这样做会更好:

try:
    do_smth1()
except Stmnh1Exception:
    # handle Stmnh1Exception

try:
    do_smth2()
except Stmnh2Exception:
    # handle Stmnh2Exception

回答by Dan

Depending on where and how often you need to do this, you could also write a function that does it for you:

根据您需要执行此操作的位置和频率,您还可以编写一个函数来为您执行此操作:

def live_dangerously(fn, *args, **kw):
    try:
        return fn(*args, **kw)
    except Exception:
        pass

live_dangerously(do_smth1)
live_dangerously(do_smth2)

But as other answers have noted, having a null exceptis generally a sign something else is wrong with your code.

但正如其他答案所指出的,空except值通常表示您的代码有其他问题。

回答by Lucas Ribeiro

You can achieve what you want, but with a different syntax. You can use a "finally" block after the try/except. Doing this way, python will execute the block of code regardless the exception was thrown, or not.

你可以实现你想要的,但使用不同的语法。您可以在 try/except 之后使用“finally”块。这样做,无论是否抛出异常,python 都会执行代码块。

Like this:

像这样:

try:
    do_smth1()
except:
    pass
finally:
    do_smth2()

But, if you want to execute do_smth2() only if the exception was not thrown, use a "else" block:

但是,如果您只想在未抛出异常时执行 do_smth2(),请使用“else”块:

try:
    do_smth1()
except:
    pass
else:
    do_smth2()

You can mix them too, in a try/except/else/finally clause. Have fun!

您也可以在 try/except/else/finally 子句中混合它们。玩得开心!

回答by SingleNegationElimination

one way you could handle this is with a generator. Instead of calling the function, yield it; then whatever is consuming the generator can send the result of calling it back into the generator, or a sentinel if the generator failed: The trampoline that accomplishes the above might look like so:

您可以处理此问题的一种方法是使用生成器。与其调用函数,不如让步;然后任何消耗生成器的东西都可以将调用它的结果发送回生成器,或者如果生成器失败则发送哨兵:完成上述操作的蹦床可能如下所示:

def consume_exceptions(gen):
    action = next(gen)
    while True:
        try:
            result = action()
        except Exception:
            # if the action fails, send a sentinel
            result = None

        try:
            action = gen.send(result)
        except StopIteration:
            # if the generator is all used up, result is the return value.
            return result

a generator that would be compatible with this would look like this:

与此兼容的生成器如下所示:

def do_smth1():
    1 / 0

def do_smth2():
    print "YAY"

def do_many_things():
    a = yield do_smth1
    b = yield do_smth2
    yield "Done"
>>> consume_exceptions(do_many_things())
YAY

Note that do_many_things()does notcall do_smth*, it just yields them, and consume_exceptionscalls them on its behalf

请注意,do_many_things()没有调用do_smth*,它只是得到他们,consume_exceptions称他们为代表的

回答by pankaj

While the other answers and the accepted one are correct and should be followed in real code, just for completeness and humor, you can try the fworitpy( https://github.com/ajalt/fworitpy) module.

虽然其他答案和接受的答案都是正确的,应该在实际代码中遵循,只是为了完整性和幽默,您可以尝试fworitpy( https://github.com/ajalt/fworitpy) 模块。

Your code can be changed to the following:

您的代码可以更改为以下内容:

@fworitpy
def myfunc():
    do_smth1()
    do_smth2()

Then calling myfunc()would call do_smth2()even if there is an exception in do_smth1())

即使有异常,调用myfunc()也会调用do_smth2()do_smth1())

Note: Please do nottry it in any real code, it is blasphemy

注:请不要尝试在任何实际的代码,它是亵渎

回答by DeWil

special_functo avoid try-except repetition:

special_func以避免 try-except 重复:

def special_func(test_case_dict):
    final_dict = {}
    exception_dict = {}

    def try_except_avoider(test_case_dict):

        try:
            for k,v in test_case_dict.items():
                final_dict[k]=eval(v) #If no exception evaluate the function and add it to final_dict

        except Exception as e:
            exception_dict[k]=e #extract exception
            test_case_dict.pop(k)
            try_except_avoider(test_case_dict) #recursive function to handle remaining functions

        finally:  #cleanup
            final_dict.update(exception_dict)
            return final_dict #combine exception dict and  final dict

    return try_except_avoider(test_case_dict) 

Run code:

运行代码:

def add(a,b):
    return (a+b)
def sub(a,b):
    return (a-b)
def mul(a,b):
    return (a*b)

case = {"AddFunc":"add(8,8)","SubFunc":"sub(p,5)","MulFunc":"mul(9,6)"}
solution = special_func(case)

Output looks like:

输出看起来像:

{'AddFunc': 16, 'MulFunc': 54, 'SubFunc': NameError("name 'p' is not defined")}

To convert to variables:

转换为变量:

locals().update(solution)

Variables would look like:

变量看起来像:

AddFunc = 16, MulFunc = 54, SubFunc = NameError("name 'p' is not defined")

回答by LIU ZHIWEN

'continue' is allowed within an 'except' or 'finally' only if the try block is in a loop. 'continue' will cause the nextiteration of the loop to start.

只有当 try 块处于循环中时,才允许在 'except' 或 'finally' 中使用 'continue'。'continue' 将导致循环的一次迭代开始。

So you can try put your two or more functions in a list and use loop to call your function.

因此,您可以尝试将两个或多个函数放在一个列表中并使用循环来调用您的函数。

Like this:

像这样:

funcs = [f,g]
for func in funcs:
    try: func()
    except: continue

For full information you can go to this link

有关完整信息,您可以转到此链接