10

I am running a cell in Jupyter notebook where an error is bound to occur after some time(usually hours). But even after this error occurs, I want the compiler to just move on to the next cell and run the remaining cells that I put in the queue to be run after this cell finishes.

I know exceptions might be able to do this, but I wanted to know if there was any other way specific to Python or Jupyter notebook that might do the trick.

Cell 1: Some code running # Error will occur here and stop the execution

Cell 2,3...,n: Some code # Code should still run after the error occurs in Cell 1

Thanks for any solutions. The help is appreciated.

Soham
  • 101
  • 1
  • 4
  • 1
    Take a look on this: https://stackoverflow.com/questions/40110540/jupyter-magic-to-handle-notebook-exceptions – Masoud Jun 01 '19 at 01:09
  • Yeah, I already looked through this thread but I wasn't able to formulate a solution using the solution suggested there. Could you try to simplify what I should do in my case specifically? The reason I am asking is that it is mentioned there that exec is not able to access variables from other cells and I need to use the final values of variables in cell 1 in the cells after that. – Soham Jun 01 '19 at 09:13

3 Answers3

6

There's no need to install any extension, at least not since notebook 5.1.

After activating tags with View > Cell Toolbar > Tags, you can add raises-exception.

Jupyter will not stop the execution after this cell, even if an exception is raised. It will also keep on running if the tag is set and no exception is raised.

Here's a Jupyter example after launching Kernel > Restart & Run All:

jupyter still running after exception

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
4

There's a Jupyter Notebook nbextensions extension called Runtools which allows you to run all cells and ignore errors with the shortcut Alt + F. See Installing jupyter_contrib_nbextensions on how to install nbextensions and enable extensions like Runtools.

mic
  • 1,190
  • 1
  • 17
  • 29
1

One way through creating a custom magic method in jupyter notebook, (adapted from this answer here):

from IPython.core.magic import register_cell_magic

@register_cell_magic('handle')
def handle(line, cell):
    try:
#         exec(cell)  # doesn't return the cell output though
        return eval(cell)
    except Exception as exc:
        print(f"\033[1;31m{exc.__class__.__name__} : \033[1;31;47m{exc}\033[0m")
#         raise # if you want the full trace-back in the notebook

Now we can add the magic command %%handle at the beginning of any cell in jupyter notebook and it will ensure that the script doesn't stop due to any error arising in that cell.

%%handle
1/0
%%handle
1/1

enter image description here

rahul-ahuja
  • 1,166
  • 1
  • 12
  • 24