In Jupyter notebook, if an error occurs in a cell, automatically run another cell containing a print statement

In a Jupyter notebook, when we “run all cells”, if an error occurs (e.g could be a zero division error, or a dataframe doesn’t exist), the notebook will stop and it might not be apparent that this has happened. This error could occur in multiple cells.

If an error does occur, is there a way to automatically run a specific cell (e.g. cell 20) further down the notebook containing a print statement to say, for example print(‘error occurred’)?

  • “…it might not be apparent that this has happened.” Not following this. What version of Jupyter specifically are you trying to address? The modern Jupyter Notebook 7+ and JupyterLab have an indicator in the upper left about status of running cells. The circle fill ticks away to visually give feedback about percent of the cells that have run when you do ‘Run All’. For example, when 3/4 of the cells are complete, the circle will be 75% filled with just a quarter left open. As for doing something than the default upon encountering an error, …

    – 

  • <continued> I think it would also help to specify versions of Jupyter tech involved. Did you see here? You can customize things and if that doesn’t work in Jupyter Notebook 7+ or JupyterLab then please raise that as a specific issue. Another thing to consider is that notebooks aren’t a good fit for all programming applications. In particular long-running computation is one that many find the traditional ways of running on the command line and using screen (or similar tools) to detach and reattach later are better.

    – 

  • As far as things not being apparent, I should also point out that JupyterLab has a status monitor in the bottom left side, too, as far as memory usage and other details. That status changing as well after you hit ‘Run All’ will also give you an idea of how things are progressing or not.

    – 

  • I just wanted to highlight the tag raises-exception that is among the related answers I linked to here. I’m seeing that work well in JupyterLab 4.0.6 and Jupyter Notebook 7.0.4 right now. I will say though that the asterisk in the execution brackets for each cell stops showing in the unrun cells once the first exception is hit; however, the cells after the exception will continue to run even though content in the brackets on the right for each cell is clear! The execution number is then correctly displayed after completion of each cell.

    – 

  • I added a notebook for testing the raises-exception tag here. The second cell currently has the tag. Because of that tag. you’ll see with ‘Run All’ the other cells will continue to run even after the division by zero error in cell #2.

    – 

Leave a Comment