Heading image

This is Day 15 of the #100DaysOfPython challenge.

This post will look at home exceptions are rescued and will demonstrate how to handle different exceptions raised.

Prerequisites

  1. Familiarity with Pipenv. See here for my post on Pipenv.
  2. Familiarity with JupyterLab. See here for my post on JupyterLab.

Getting started

Let’s create the directory and install Pillow.

Now we can start up the notebook server.

The server will now be up and running.

Creating the notebook

Once on http://localhost:8888/lab, select to create a new Python 3 notebook from the launcher.

Ensure that this notebook is saved in .

We will create four cells to handle four parts of this mini project:

  1. A demonstration on how works.
  2. Looking at raising an error from a function.
  3. Creating and using custom errors.

Try/Except

We can use the statement to handle errors. You an whenever you want to throw an error from a code block.

The is self can then be delegated higher up the code chain to be handled.

For example, if we execute this in our first JupyterLab code block:

We notice the output is . We do not make it passed the raised exception.

We can also capture exceptions by their type. For example, if we execute this in our second JupyterLab code block:

You will notice that was captured and printed, where as the final code block is used a capture all.

Raising an error from a function

Defining a function that raises an error will traverse up the code block to the top level.

This also prints out .

Creating and using custom errors

We can create custom errors simply by defining a class that extends .

We can see this in action working randomly when we use the function as a helper to determine which error to raise:

Running this code in a block will print out or based on the random value.

That means that our is being handled in the block.

Summary

Today’s post demonstrated how to create custom errors by extending and demonstrating how errors are raised in a simple manner.

Managing errors in Python is a necessity when working with more complex code that requires more fine-grained control over the possible error outcomes.

Resources and further reading

  1. The ABCs of Pipenv
  2. Hello, JupyterLab
  3. Pipenv
  4. Python Exceptions — An Introduction
  5. User Defined Exceptions in Python

Photo credit:

Originally posted on my blog. To see new posts without delay, read the posts there and subscribe to my newsletter.

I write content for AWS, Kubernetes, Python, JavaScript and more. To view all the latest content, be sure to visit my blog and subscribe to my newsletter. Follow me on Twitter.

Senior Engineer @ UsabilityHub. Formerly Culture Amp.