不要捕获异常,甚至从try块中 [英] Don't catch exceptions, even from within a try block

查看:95
本文介绍了不要捕获异常,甚至从try块中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个结构良好的OOP Python应用程序,其中每个对方法的调用都包含在一个try块中。现在假设我正在调试这个应用程序,我想要实际抛出的异常!如果真的:,请将每个 try 行替换为,并注释掉 除了:部分,只是为了调试。有没有办法告诉Python解释器一个特定部分抛出的异常的代码应该停止程序执行并将异常信息打印到stdout?

Suppose a well-structured OOP Python application, where every call to a method is wrapped in a try block. Now suppose that I'm debugging this application and I want the exceptions to actually be thrown! It would be neigh impossible to replace every try: line with if True: and to comment out """ the except: portions, just to debug. Is there any way to tell the Python interpreter that an exceptions thrown by a specific portion of code should stop program execution and print the exception information to stdout?

Kubuntu Linux上的Python 2.7.3或3.2.3。

Python 2.7.3 or 3.2.3 on Kubuntu Linux.

推荐答案


假设一个结构良好的OOP Python应用程序,其中每个调用一个方法都被包装在一个try块中... / p>

"Suppose a well-structured OOP Python application, where every call to a method is wrapped in a try block ... "

这根本听不到我的结构,异常处理的一个基本原则是只有手柄例外您知道如何处理,这是您将看到的常见不要使用裸露的语句的驱动原则:

this doesn't sound well-structured to me at all. One of the basic principles of exception handling is ONLY HANDLE EXCEPTIONS THAT YOU KNOW HOW TO DEAL WITH. This is the driving principle behind the common "don't use a bare except" statement that you'll see:

try:
   do_something()
except:   #BAD BAD BAD
   react_to_exception()

被特定部分代码抛出...我们在说一些代码的具体特点?如果它是一个单独的块,你可以随时重新加注:

"Thrown by a specific portion of code" ... How specific a section of code are we talking about? If it's a single block, you can always re-raise:

try:
    do_something()
except ValueError as e:
    raise e

这篇关于不要捕获异常,甚至从try块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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