Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

How to catch ImportError Exception in Python?



The ImportError exception in Python is raised when the interpreter cannot find or load a module that is being imported using the import statement. 

Catching the ImportError Exception

Like any other exception, we can catch the ImportError exception using the try-except blocks. In this article, we discuss various scenarios where the ImportError exception occurs, with examples, and catch the generated exception using the try-except blocks in each scenario.

When Does ImportError Occur?

The ImportError generally occurs in the following cases -
  • Trying to import a module that doesn't exist.
  • Misspelling the module name.
  • Trying to import a function or class that is not available in the specified module.

Example: Importing a Nonexistent Module

In the following example, we try to import a module that does not exist. This raises an ImportError and we are catching the generated exception -

try:
   import not_a_real_module
except ImportError:
   print("Module could not be imported.")

Since the module, not_a_real_module does not exist, the program catches the error and prints a message -

Module could not be imported.

Example: Importing a Nonexistent Function from a Module

In the following example, we are trying to import a function that is not present in the given module. Here, as the function imaginary_function() is not defined in the math module, an ImportError is raised, and we handled it.

try:
   from math import imaginary_function
except ImportError:
   print("Function could not be imported from module.")

We get the output as shown below -

Function could not be imported from module.

Example: Handling ImportError with Alternative Module

Sometimes, you may need to use an alternative module if the desired one is unavailable. In such cases, we can use the ImportError exception as shown below -

try:
   import numpy as np
   print("NumPy imported successfully.")
except ImportError:
   print("NumPy is not available, using built-in alternatives.")

The output below appears if NumPy is not installed -

NumPy is not available, using built-in alternatives.

If NumPy is installed in your system, you will get the following output -

NumPy imported successfully.
Updated on: 2025-06-07T19:42:48+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements