开发者

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

开发者 https://www.devze.com 2023-03-14 07:07 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Don't show Python raise-line in the exception stack
This question already has answers here: Closed 11 years ago.

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 writi开发者_开发问答ng c code)?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号