在python程序中引发手动异常是否会终止它? [英] Does raising a manual exception in a python program terminate it?

查看:212
本文介绍了在python程序中引发手动异常是否会终止它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中调用抬高语句会导致程序以回溯退出还是从下一条语句继续执行程序?我想提出一个例外,但继续执行其余的程序。
好​​吧,我需要这样做,因为我正在第三方系统中运行该程序,并且希望引发异常,但继续执行该程序。有关代码是必须返回的线程函数。
我不能为引发异常并让程序继续生成新线程吗?

Does invoking a raise statement in python cause the program to exit with traceback or continue the program from next statement? I want to raise an exception but continue with the remainder program. Well I need this because I am running the program in a thirdparty system and I want the exception to be thrown yet continue with the program. The concerned code is a threaded function which has to return . Cant I spawn a new thread just for throwing exception and letting the program continue?

推荐答案


我想提出一个例外,但继续执行其余程序。

I want to raise an exception but continue with the remainder program.

这没有什么意义:程序控制要么继续通过代码,或者使调用栈达到最近的 try 块。

There's not much sense in that: the program control either continues through the code, or ripples up the call stack to the nearest try block.

相反,您可以尝试一些:

Instead you can try some of:


  • traceback 模块(用于阅读或检查您一起看到的追溯信息

  • logging 模块(用于在程序运行时保存诊断)

  • the traceback module (for reading or examining the traceback info you see together with exceptions; you can easily get it as text)
  • the logging module (for saving diagnostics during program runtime)

示例:

def somewhere():
    print 'Oh no! Where am I?'
    import traceback
    print ''.join(traceback.format_stack())  # or traceback.print_stack(sys.stdout)
    print 'Oh, here I am.'

def someplace():
    somewhere()

someplace()

输出:

Oh no! Where am I?
  File "/home/kos/exc.py", line 10, in <module>
    someplace()
  File "/home/kos/exc.py", line 8, in someplace
    somewhere()
  File "/home/kos/exc.py", line 4, in somewhere
    print ''.join(traceback.format_stack())

Oh, here I am.

这篇关于在python程序中引发手动异常是否会终止它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆