[英]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.如您所见,无论如何,每次都会
print('Executed')
行。 My goal is to stop the execution of the current function right after except ValueError
is caught.我的目标是在异常
except ValueError
被捕获后立即停止当前 function 的执行。
This function is a part of the multithreaded algorithm.这个 function 是多线程算法的一部分。 So, if this function cannot be executed because of
except ValueError
- this function should stop and does not return anything.所以,如果这个 function 因为
except ValueError
而不能执行 - 这个 function 应该停止并且不返回任何东西。 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.
如果您使用 try ,除非您基本上希望程序在发现错误时不要停止执行。 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.
更新后编辑:您可以将返回添加到 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.您可以使用
exit("Failure")
退出 Python 脚本,其中字符串是可选消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.