Don't catch exceptions, even from within a try block

不打扰是莪最后的温柔 提交于 2019-12-25 01:44:46

问题


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?

Python 2.7.3 or 3.2.3 on Kubuntu Linux.


回答1:


"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  # or `raise` or `raise SomeOtherError() from e` in more modern pythons.



回答2:


This sound like a job for a debugger. I'm only familiar with the debugger for PyCharm, with which you can set an exception breakpoint for any exception.




回答3:


If I understood your question correctly, I think you want stack trace for debugging purpose. In such case,you can use traceback module where ever you want:

import traceback

try:
    func()
except Exception,e:
    print traceback.format_exc()

Or use debugger - pdb



来源:https://stackoverflow.com/questions/17025010/dont-catch-exceptions-even-from-within-a-try-block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!