Raising exceptions without 'raise' in the traceback? [duplicate]

佐手、 提交于 2019-12-01 02:34:54

问题


Possible Duplicate:
Don't show Python raise-line in the exception stack

Built in exceptions like NameError etc. give me a traceback to the point in my code where the exception occurred. I'm working on a utility module and it bugs me that if code using my module raises and exception the last thing in the traceback before the exception is my raise WhateverError.

Is there any way to raise an exception in python and have the tracback stop one frame up ala the builtin exceptions (without writing c code)?


回答1:


Pure Python doesn't provide a way to mutate existing traceback objects or create arbitrary traceback objects.

>>> exc_info[2].tb_next = None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: readonly attribute

>>> types.TracebackType()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot create 'traceback' instances

Note that if it were possible to do this you wouldn't just affect the default formatting of tracebacks, you'd also interfere with people's ability to use pdb to post-mortem errors in your utility module.

If the traceback is being logged or otherwise formatted by your utility module then you can just not include the frames you consider uninteresting in the output. For instance, the standard library's unittest module does this when reporting errors that occur while running tests.



来源:https://stackoverflow.com/questions/6410764/raising-exceptions-without-raise-in-the-traceback

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