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

问题描述 投票:1回答:2

给出以下简单示例:

while True:

    readme = input("Write here something:")

    if readme == "":

        raise Exception("That was empty!")

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

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

python exception
2个回答
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!")

0
投票

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

如果您不在上述链中的任何位置处理异常,则解释器只是将其抛出给用户。

© www.soinside.com 2019 - 2024. All rights reserved.