jupyter: how to stop execution on errors?

Question:

The common way to defensively abort execution in python is to simply do something like:

if something_went_wrong:
    print("Error message: goodbye cruel world")
    exit(1)

However, this is not good practice when using jupyter notebook, as this seems to abort the kernel entirely, which is not always wanted. Is there are proper/better way in jupyter, besides hack-y infinite loops?

Asked By: gustafbstrom

||

Answers:

No, exit() is not the way to abort Python execution usually.
exit() is meant to stop the interpreter immediately with a status code.

Usually, you will write a script like that:

 if __name__ == '__main__':
     sys.exit(main())

Try not to put sys.exit() in the middle of your code — it is bad practice,
and you might end up with non closed filehandle or locked resources.

To do what you want, just raise an exception of the correct type. If it propagate to the eval loop, IPython will stop the notebook execution.

Also, it will give you useful error messages and a stack trace.

if type(age) is not int:
    raise TypeError("Age must be an integer")
elif age < 0:
    raise ValueError("Sorry you can't be born in the future")
else :
    ...

You can even inspect the stack post-mortem with %debug to see what went wrong where, but that is another subject.

Answered By: Matt
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.