How to access re-raised exception in Python 3?
<p>In Python 3, there's a <a href="https://blog.ionelmc.ro/2014/08/03/the-most-underrated-feature-in-python-3/" rel="nofollow">useful <code>raise ... from ...</code> feature</a> to re-raise an exception. That said, how do you find the original (/ re-raised) exception from the raised exception? Here's a (silly) example with comments to demonstrate what I mean--</p>

<pre><code>def some_func():
    try:
      None() # TypeError: 'NoneType' object is not callable
    except as err:
      raise Exception("blah") from err

try:
    some_func()
except as err:
    # how can I access the original exception (TypeError)?
</code></pre>

<p>It's in the <code>__cause__</code> attribute of the raised exception. Taken from the <a href="https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement" rel="nofollow">docs on the <code>raise</code> statement</a> it says regarding <code>raise ... from ...</code>:</p>

<blockquote>
  <p>The <code>from</code> clause is used for exception chaining: if given, the second expression must be another exception class or instance, <em>which will then be attached to the raised exception as the <code>__cause__</code> attribute</em> (which is writable). If the raised exception is not handled, both exceptions will be printed.</p>
</blockquote>

<p>So, in your given scenario, <code>repr</code>ing the <code>__cause__</code> attribute:</p>

<pre><code>def some_func():
    try:
      None() # TypeError: 'NoneType' object is not callable
    except TypeError as err:
      raise Exception("blah") from err

try:
    some_func()
except Exception as er:
    print(repr(er.__cause__))
</code></pre>

<p>Will print out:</p>

<pre><code>TypeError("'NoneType' object is not callable",)
</code></pre>

python python-3.x exception exception-handling