26 python fallback exception-handling exception try-catch
是否有可能在Python中捕获任何错误?我不关心具体的例外是什么,因为它们都将具有相同的后备.
lun*_*chs 35
except
单独使用将捕获任何除了段错误之外的异常.
try:
something()
except:
fallback()
Run Code Online (Sandbox Code Playgroud)
如果需要使用它来退出脚本,您可能需要单独处理KeyboardInterrupt:
try:
something()
except KeyboardInterrupt:
return
except:
fallback()
Run Code Online (Sandbox Code Playgroud)
还有你可以捕捉基本异常的一个很好的名单在这里.我也非常喜欢用于从异常中检索调用堆栈的回溯模块.尝试traceback.format_exc()
或traceback.print_exc()
在异常处理程序中.
Tje*_*les 27
try:
# do something
except Exception, e:
# handle it
Run Code Online (Sandbox Code Playgroud)
对于Python 3.x:
try:
# do something
except Exception as e:
# handle it
Run Code Online (Sandbox Code Playgroud)
war*_*iuc 11
您可能还需要查看sys.excepthook:
当引发异常并且未被捕获时,解释器使用三个参数调用sys.excepthook,异常类,异常实例和回溯对象.在交互式会话中,这发生在控制返回到提示之前; 在Python程序中,这发生在程序退出之前.可以通过为sys.excepthook分配另一个三参数函数来自定义这种顶级异常的处理.
例:
def except_hook(type, value, tback):
# manage unhandled exception here
sys.__excepthook__(type, value, tback) # then call the default handler
sys.excepthook = except_hook
Run Code Online (Sandbox Code Playgroud)
引用赏金文本:
我希望能够捕获任何异常,甚至是奇怪的异常,例如键盘中断甚至系统退出(例如,如果我的 HPC 管理器抛出错误)并获取异常对象 e 的句柄,无论它可能是什么。我想处理 e 并自定义打印,甚至通过电子邮件发送
查看异常层次结构,您需要捕获BaseException
:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
Run Code Online (Sandbox Code Playgroud)
这将捕获KeyboardInterrupt
, SystemExit
, and GeneratorExit
,它们都继承自BaseException
但不继承自Exception
,例如
try:
raise SystemExit
except BaseException as e:
print(e.with_traceback)
Run Code Online (Sandbox Code Playgroud)
不提及您想要处理的异常类型本身就可以完成任务。
尝试这个:
try:
#code in which you expect an exception
except:
#prints the exception occured
Run Code Online (Sandbox Code Playgroud)
如果你想知道发生的异常类型:
try:
# code in which you expect an exception
except Exception as e:
print(e)
# for any exception to be catched
print(type(e))
# to know the type of exception.
Run Code Online (Sandbox Code Playgroud)
有关详细说明,请访问 https://www.tutorialspoint.com/python/python_exceptions.htm
归档时间: |
|
查看次数: |
30784 次 |
最近记录: |