Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 782
underrun Avatar asked Jun 20 '11 11:06

underrun


People also ask

How do you raise an exception from another exception?

Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement.

Can we use raise without exception in Python?

Only an exception handler (or a function that a handler calls, directly or indirectly) can use raise without any expressions.

How do I manually raise exceptions?

Throwing exceptions manually There are two types of exceptions user defined and predefined each exception is represented by a class and which inherits the Throwable class. To throw an exception explicitly you need to instantiate the class of it and throw its object using the throw keyword.

Does increasing exception stop execution?

except block is completed and the program will proceed. However, if an exception is raised in the try clause, Python will stop executing any more code in that clause, and pass the exception to the except clause to see if this particular error is handled there.


1 Answers

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.

like image 140
spiv Avatar answered Sep 24 '22 01:09

spiv