python:我怎么知道发生了什么类型的异常? [英] python: How do I know what type of exception occurred?

查看:17
本文介绍了python:我怎么知道发生了什么类型的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个被主程序调用的函数:

I have a function called by the main program:

try:
    someFunction()
except:
    print "exception happened!"

但是在函数执行的过程中它引发了异常,所以它跳转到了except部分.

but in the middle of the execution of the function it raises exception, so it jumps to the except part.

我如何才能准确地看到导致异常发生的 someFunction() 中发生了什么?

How can I see exactly what happened in the someFunction() that caused the exception to happen?

推荐答案

其他答案都指出你不应该捕获泛型异常,但似乎没有人想告诉你为什么,这对于理解何时可以打破规则".这里是一个解释.基本上,这样你就不会隐藏:

The other answers all point out that you should not catch generic exceptions, but no one seems to want to tell you why, which is essential to understanding when you can break the "rule". Here is an explanation. Basically, it's so that you don't hide:

因此,只要您注意什么都不做,就可以捕获通用异常.例如,您可以通过另一种方式向用户提供有关异常的信息,例如:

So as long as you take care to do none of those things, it's OK to catch the generic exception. For instance, you could provide information about the exception to the user another way, like:

  • 在 GUI 中将异常显示为对话框
  • 将异常从工作线程或进程传输到多线程或多处理应用程序中的控制线程或进程

那么如何捕捉通用异常呢?有几种方法.如果您只想要异常对象,请这样做:

So how to catch the generic exception? There are several ways. If you just want the exception object, do it like this:

try:
    someFunction()
except Exception as ex:
    template = "An exception of type {0} occurred. Arguments:
{1!r}"
    message = template.format(type(ex).__name__, ex.args)
    print message

确保确保 message 以一种难以错过的方式引起用户的注意!如果消息隐藏在许多其他消息中,则打印它(如上所示)可能还不够.未能引起用户的注意无异于吞下所有的例外情况,如果在阅读本页的答案后您应该留下一个印象,那就是这不是一件好事.使用 raise 语句结束 except 块将通过透明地重新引发捕获的异常来解决问题.

Make sure message is brought to the attention of the user in a hard-to-miss way! Printing it, as shown above, may not be enough if the message is buried in lots of other messages. Failing to get the users attention is tantamount to swallowing all exceptions, and if there's one impression you should have come away with after reading the answers on this page, it's that this is not a good thing. Ending the except block with a raise statement will remedy the problem by transparently reraising the exception that was caught.

上面和只使用 except: 不带任何参数的区别是双重的:

The difference between the above and using just except: without any argument is twofold:

  • 一个空的 except: 没有给你检查的异常对象
  • 上面的代码没有捕获异常SystemExitKeyboardInterruptGeneratorExit,这通常是您想要的.请参阅异常层次结构.
  • A bare except: doesn't give you the exception object to inspect
  • The exceptions SystemExit, KeyboardInterrupt and GeneratorExit aren't caught by the above code, which is generally what you want. See the exception hierarchy.

如果您还想要在没有捕获异常的情况下获得的堆栈跟踪,您可以像这样获得(仍在except子句中):

If you also want the same stacktrace you get if you do not catch the exception, you can get that like this (still inside the except clause):

import traceback
print traceback.format_exc()

如果您使用 logging 模块,您可以像这样将异常打印到日志中(连同一条消息):

If you use the logging module, you can print the exception to the log (along with a message) like this:

import logging
log = logging.getLogger()
log.exception("Message for you, sir!")

如果您想深入挖掘并检查堆栈,查看变量等,请使用 post_mortem pdb 模块在 except 块内的函数:

If you want to dig deeper and examine the stack, look at variables etc., use the post_mortem function of the pdb module inside the except block:

import pdb
pdb.post_mortem()

我发现最后一种方法在追捕错误时非常有用.

I've found this last method to be invaluable when hunting down bugs.

这篇关于python:我怎么知道发生了什么类型的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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