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

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

问题描述

  try:
someFunction()
除了:
打印异常发生!

但是在执行函数的中间引发异常,所以它跳转到code>除了部分。



如何查看 someFunction()导致异常发生?

解决方案

其他答案都指出你不应该捕捉泛型异常,但没有人似乎想告诉你为什么,这对于理解什么时候可以打破规则是至关重要的。 这里是一个解释。基本上是这样的,你不要隐藏:





所以只要你小心不要做这些事情,可以抓住泛型异常。例如,您可以以另一种方式向用户提供有关异常的信息,例如:




  • 将异常作为GUI中的对话框呈现

  • 将异常从工作线程或进程转移到多线程或多处理应用程序中的控制线程或进程



那么如何捕捉泛型异常?有几种方法如果您只想要异常对象,请执行以下操作:

  try:
someFunction()
除了例外:
template =发生类型为{0}的异常参数:\\\
{1!r}
message = template.format(type(ex).__ name__,ex .args)
打印消息

确保 消息以令人难以置信的方式引起用户的关注!如上所示打印它可能不足够,如果消息被埋在许多其他消息中。没有得到用户的注意力等于吞下所有的例外,如果有一个印象,你应该在阅读本页面的答案后才能看出来,那就是这不是一件好事。结束一个 raise 语句的区块将通过透明地重新引导被捕获的异常来解决问题。



上述之间的差异仅使用,除了:没有任何参数是双重的:




  • 一个裸露的除了:不给你检查的例外对象

  • 例外 SystemExit KeyboardInterrupt GeneratorExit 不被上述代码所捕获,这通常是您想要的。请参阅例外层次结构



如果你也想要同样的堆栈跟踪,如果你没有捕获异常,你可以得到这样(仍然在except子句中):

  import traceback 
print traceback.format_exc()

如果您使用 logging 模块,您可以将日志(以及消息)的异常打印为:

  import logging 
log = logging.getLogger()
log.exception(给你的消息,先生!)

如果你想深入挖掘堆栈,查看变量等,使用 post_mortem 功能的 pdb Ë xcept块:

  import pdb 
pdb.post_mortem()
/ pre>

我发现最后一种方法在追捕错误时是无价的。


I have a function called by the main program:

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

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

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:

  • Present exceptions as dialogs in a GUI
  • Transfer exceptions from a worker thread or process to the controlling thread or process in a multithreading or multiprocessing application

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:\n{1!r}"
    message = template.format(type(ex).__name__, ex.args)
    print message

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.

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

  • 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.

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

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!")

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天全站免登陆