简体   繁体   English

子函数出错时如何终止Python中的一行代码

[英]How to terminate a line of code in Python when sub-function errors

So I have some code that is in its simple structure like the code below.所以我有一些代码结构简单,如下面的代码。 Basically I have two functions.基本上我有两个功能。 One function takes the other as an input.一个函数将另一个作为输入。 What I want to have happen is if the function1 fails and would error, that it "exits" out and skips over the function2(function1()) line and continues on without ending the entire process.我想要发生的是,如果 function1 失败并且会出错,它会“退出”并跳过 function2(function1()) 行并继续而不结束整个过程。

def function1():
     try:
          something = some_function()
          return something
     except:
          exit()

def function2(input):
     operate(input)


function2(function1())

Anyone have any ideas/suggestions?任何人有任何想法/建议?

instead of exit , have it return an expected output --而不是exit ,让它返回一个预期的输出——

def function1():
     try:
          something = some_function()
          return something
     except Exception as e:
          print(f"Something went wrong: {e}")
          return False

Then you can act based on it's boolean condition --然后你可以根据它的布尔条件采取行动——

def function2(input):
    if input:
        operate(input)

Ending the entire process is exactly what exit does.结束整个过程正是exit所做的。 You should just let the exception go uncaught, and execute function2(function1()) in a try statement.您应该让异常未被捕获,并在try语句中执行function2(function1())

def function1():
    return some_function()

def function2(i):
    operate(i)

try:
    function2(function1())
except Exception:
    pass

If function1 isn't a function you have control over, you can specifically catch SystemExit that exit raises, though I would do so in as small a block of code as possible.如果function1不是您可以控制的函数,您可以专门捕获exit引发的SystemExit ,尽管我会在尽可能小的代码块中这样做。

try:
    x = function(1)
except SystemExit:
    pass
else:
    function2(x)

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

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