如何引发Exception并继续使用Python中的主代码

时间:2017-12-21 12:13:59

标签: python exception

给出以下简单示例:

while True:

    readme = input("Write here something:")

    if readme == "":

        raise Exception("That was empty!")

(1)抛出异常后,主代码/循环如何继续工作? (2)如果我们同时运行另一个线程,我们如何在那里捕获异常?

编辑:是否可以在循环内没有try / except块的情况下执行此操作?

2 个答案:

答案 0 :(得分:1)

是的,可以使用try / except。

尝试制作这样的功能:

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.')

然后致电:

myexception('That was empty!)

例如(来自示例):

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!")

答案 1 :(得分:0)

不使用try / catch在python中是不可能的。当我们在python中调用一个函数并引发异常时,异常会传播到调用函数并继续。

如果您没有在上述链中的任何地方处理异常,则解释器只是将其抛给用户。