python如何吞任何形式的异常?
ringa_lee
ringa_lee 2017-04-18 10:33:44
0
2
511

经常看到有些模块,任何异常都不会崩溃,然后还是继续运行代码,自己试过在程序最外面加上try ----catch----但是好像并不能把所有错误信息都吞了,好像只对块内代码起作用,要是跳到另外的方法仍然会抛出异常,那种吞异常的是怎么写的呀?我现在有个需求要求代码一直跑。即使有异常也不能退出。。。请教各位大神指点

ringa_lee
ringa_lee

ringa_lee

reply all(2)
Ty80

This requires encapsulating a framework, however any errors you describe continue to run. This requirement is that you assume that even if there is an error, it will not affect the running results of the program. This means that you can control the scope of the error yourself. If the probability of such an error is high and it is not fatal, you hope to pass it on the main The thread captures and any exception is eventually thrown through the program entry. So you should do the capture in the program run startup block.

try:
    main()
except:
    pass

This method will also exit when an exception occurs, if you want to continue trying. You can add a loop

while time_out < max_time_out:
    try:
        main()
    except:
        pass
        timeout+=100

But this method requires you to know very well that the program will work normally after several attempts, otherwise it will still exit.
Finally, what I want to say is that when the program hangs due to an exception, it reminds you that you really should fix it instead of ignoring it. If you ignore it and you can continue to run but it will bring wrong results, you will regret it~

刘奇

should be

try....except

In addition, if you add try..except in the outermost layer, when the program makes an error, it will only catch the error in the outermost layer, and then exit. I have a way, but after an error, you can only start over (it is best to find the error) place)

import sys

def main():
    print(1)
    int('s')

def main1():
    print(2)
    while True:
        try:
            main()
        except KeyboardInterrupt:
            sys.exit()
        except Exception:
            pass

if __name__ == '__main__':
    main1()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!