How to simply handle errors when importing modules in Python

Based on my personal experience with the Python computer programming language, the builtin import statement is being used to make use of different modules part of the Python technology.

For example, when a Python coder needs the functionalities included in the os builtin module, they have to import it by making use of the code which is shown below.

import os

Before going any further with this tutorial, make sure to launch a new interactive console on your own operating system so you can practice the commands part of the Python computer programming language by yourself.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Once the above piece of Python code got executed on my interactive console, no error was thrown, but there are times when the module you want to work with is not shipped by default.

And when the module which you try to import is not included in the standard library of the Python computer programming language, for sure that an error will be thrown on your interactive console or application.

Once you have managed to launch a new Python interactive console on your own operating system, make sure to run the following command.

import nothing

Once the above piece of Python code got executed on my own operating system, I got the following error.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named nothing

As you can see from the above output, the Python traceback information informs the user that the module named nothing does not exist in the standard library.

How to handle errors like the one being shown above? Being very rich in features, the Python computer programming language offers the try/except utilities which can be easily used to handle errors.

The example shown below, is a nice illustration of the try/except block in a practical case.

try:
    import nothing
except ImportError:
    print('Module does not exist')

Final thoughts

There are many cases when the Python coder needs to import a module in their application and immediately check if the process worked or not. The try/except block is the perfect utility when it comes to handling errors in Python applications.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Leave a Reply

Your email address will not be published. Required fields are marked *

*