Jupyter magic to handle notebook exceptions
<p>I have a few long-running experiments in my Jupyter Notebooks. Because I don't know when they will finish, I add an email function to the last cell of the notebook, so I automatically get an email, when the notebook is done.</p>

<p>But when there is a random exception in one of the cells, the whole notebook stops executing and I never get any email. <strong>So I'm wondering if there is some magic function that could execute a function in case of an exception / kernel stop.</strong></p>

<p>Like</p>

<pre><code>def handle_exception(stacktrace):
    send_mail_to_myself(stacktrace)


%%in_case_of_notebook_exception handle_exception # &lt;--- this is what I'm looking for
</code></pre>

<p>The other option would be to encapsulate every cell in try-catch, right? But that's soooo tedious.</p>

<p>Thanks in advance for any suggestions.</p>

<p>I don't think there is an out-of-the-box way to do that not using a <code>try..except</code> statement in your cells. AFAIK <a href="https://github.com/ipython/ipython/issues/1977" rel="nofollow">a 4 years old issue</a> mentions this, but is still in open status.</p>

<p>However, the <a href="https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tree/master/src/jupyter_contrib_nbextensions/nbextensions/runtools" rel="nofollow">runtools extension</a> may do the trick.</p>

python jupyter jupyter-notebook