简体   繁体   中英

How to stop the execution of a function right after the exception happened? [Python]

Let's say I have following code:

def main():
  try:
    int('string_for_ValueError')
  except ValueError:
    print('How to stop further execution right here?')
  print('Executed')

main()

As you can see, print('Executed') line will be executed every time no matter what. My goal is to stop the execution of the current function right after except ValueError is caught.

So, the question is - how to do that?

UPDATE

This function is a part of the multithreaded algorithm. So, if this function cannot be executed because of except ValueError - this function should stop and does not return anything. But other threads should work after that.

You can simple raise an error with a message to stop execution. If you are using try except you basically want the program not to stop from execution when errors found. If you really want to do that, you can do it this way, but you can do it several ways. My question is why you are catching this error if you want to stop the program?

EDIT AFTER YOUR UPDATE: You can add return to your function.

def main():
  try:
    int('string_for_ValueError')
  except ValueError:
    print('How to stop further execution right here?')
    return "to something"
  print('this line not executed because function sees the return')

main()

You can quit a Python script using exit("Failure") where the string is an optional message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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