In Python 2, How to raise a Python error without changing its traceback?
<p>In the following typical try-except block:</p>

<pre><code>try:
    do something
except Exception as e:
    {clean up resources}
    raise e
          ^
</code></pre>

<p>However, this will print out an error message with traceback pointing to ^, where the error is raised, in contrast to most other languages, where the traceback of e when it is first generated is remembered and printed instead.</p>

<p>The Python style of handling exception creates significant difficulty in figuring out the source of the error, and I would like to override it. Is there a simple way of doing this?</p>

<p>To catch an exception, do something with it and then re-raise the same exception:</p>

<pre><code>try:
    do something
except Exception as e:
    {clean up resources}
    raise   # raises the same exception with the same traceback
</code></pre>

<p>To catch an exception, raise a new exception, but keep the old traceback:</p>

<pre><code>try:
    do something
except Exception as e:
    exctype, value, traceback = sys.exc_info()
    raise NewException, 'Argument for new exception', traceback
</code></pre>

<p>This is described in <a href="https://docs.python.org/2.7/reference/simple_stmts.html#the-raise-statement" rel="nofollow">Python 2.7 specification section 6.9</a>:</p>

<blockquote>
  <p>If no expressions are present, raise re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a TypeError exception is raised indicating that this is an error (if running under IDLE, a Queue.Empty exception is raised instead).</p>
  
  <p>Otherwise, raise evaluates the expressions to get three objects, using None as the value of omitted expressions. The first two objects are used to determine the type and value of the exception.</p>
  
  <p>...</p>
  
  <p>If a third object is present and not None, it must be a traceback object (see section The standard type hierarchy), and it is substituted instead of the current location as the place where the exception occurred.</p>
</blockquote>

<h2>Python 3</h2>

<p>Note that in Python 3, the original traceback is always preserved when raising from the <code>except</code> block. In other cases, syntax <code>raise Exception() from another_exception</code> is used.</p>

python exception exception-handling