在异常块中继续?

0 投票
2 回答
50 浏览
提问于 2025-04-12 19:39

我的研究显示不行,但我在想有没有更简洁的方法来处理以下情况:

try:
    some_function()
except Exception:
    # process some data to determine how to handle the error
    if not some_statement:
        # do some_function() in a different way
        #### Here I want to continue to the remaining code after the exception
    # a bunch of code if some_statement==True
# remaining code

显而易见的解决办法就是把if语句后面的所有内容放到else里,但我发现我的缩进已经比我想要的多了。

有没有我忽略的内置功能?看起来应该有办法在异常处理时继续或跳出,但似乎这些功能只适用于循环。

2 个回答

0

我会尽量说得清楚一些。如果你有其他想要了解的内容,请在评论里告诉我。

try:
    some_function()
except Exception as e:
    if not some_statement:
        # do some_function() in a different way
        some_alternative_function()
        # 2. way is, you can pass a parameter to the function
        # some_function(blabla=True)
        # 3. way is, you can wrap the whole try-except clause with a function and make a recursive call here
    else:
        # a bunch of code if some_statement==True
        handle_error_some_statement_true(e)
else:
    # code to execute if some_function() did not raise an exception
    post_some_function_success()
1

用户 @Barmar 确认了我的想法。

对于某些应用来说,把代码分成不同的函数确实是有道理的,但在我的情况下,some_function() 只是一个脚本中很小的一部分,只适用于一个非常特定的场景。虽然这样做可以让我的主函数看起来更简洁,但这些函数没有其他用途,我觉得这样反而会让脚本变得不容易读懂。

所以我会接受多出来的缩进,因为我知道没有更好的办法。

谢谢大家!

撰写回答