简体   繁体   English

如何引发异常并继续执行 Python 中的主要代码

[英]How to raise an Exception and still continue the main code in Python

Given the following simple example:给定以下简单示例:

while True:

    readme = input("Write here something:")

    if readme == "":

        raise Exception("That was empty!")

(1) How can the main code / loop continue to work after an Exception has been thrown? (1) 抛出异常后,主代码/循环如何继续工作? (2) And if we simultaneously run another thread, how can we catch the Exception in there? (2) 如果我们同时运行另一个线程,我们如何捕获那里的异常?

Edit: is it possible to do this without having a try/except block inside the loop?编辑:是否可以在循环内没有 try/except 块的情况下执行此操作?

Yes it is possible with try/except.是的,可以使用 try/except。

Try making a function like so:尝试像这样制作 function:

from inspect import currentframe,getframeinfo
def Raise(ex):

    cf = currentframe()
    #Get the line
    line=cf.f_back.f_lineno
    print('Traceback:\n'+ex+'\nin line '+str(line))
    wait=input('Press Enter to continue excecution.')

And then call:然后调用:

myexception('That was empty!)

For example (from the example):例如(来自示例):

from inspect import currentframe,getframeinfo

    def Raise(ex):
    cf = currentframe()
    #Get the line
    line=cf.f_back.f_lineno
    print('Traceback:\n'+ex+'\nin line '+str(line))
    wait=input('Press Enter to continue excecution.')

readme = input("Write here something:")
if readme == "":
    Raise("That was empty!")

Without using the try/catch it is not possible in python. When we call a function in python and it raises a exception, the exceptions is propagated to the caller function and it continues.如果不使用 try/catch,在 python 中是不可能的。当我们在 python 中调用 function 并引发异常时,异常会传播到调用者 function 并继续。

If you do not handle the the exception anywhere in the above chain, interpreter just throw it out to the user.如果您不处理上述链中任何地方的异常,解释器只会将其抛给用户。

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

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