捕获Python中的任何错误

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()在异常处理程序中.

  • 捕获`除了异常'通常更好的做法 - KeyboardInterrupt和SystemExit不从Exception继承,所以你仍然可以"爆发".当然,取决于你正在做什么. (3认同)
  • 但我想指向“e”异常,无论类型如何。 (2认同)

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)

  • @CharlieParker这是不同的,因为在这种情况下你可以访问“Exception”对象。 (4认同)
  • 这与接受的答案有何不同?我看到代码不同,但你介意添加一些评论/细节吗? (2认同)
  • 异常不会捕获所有错误,但是会捕获所有错误。 (2认同)

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)


Chr*_*nds 6

引用赏金文本:

我希望能够捕获任何异常,甚至是奇怪的异常,例如键盘中断甚至系统退出(例如,如果我的 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)


gil*_*yle 5

不提及您想要处理的异常类型本身就可以完成任务。

尝试这个:

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