search

Home  >  Q&A  >  body text

python如何吞任何形式的异常?

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

ringa_leeringa_lee2821 days ago539

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:35:44

    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~

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:35:44

    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()
    

    reply
    0
  • Cancelreply