Python3.8: What's the difference between ImportError and ModuleNotFoundError

Viewed 2557

In python3.8, what's the difference between ImportError and ModuleNotFoundError? I'm just wondering what the difference is and why they matter.

2 Answers

ModuleNotFoundError is a kind of ImportError:

>>> issubclass(ModuleNotFoundError, ImportError)
True

It's raised specifically when the module cannot be found at all. Other problems can occur after the file is found, but during the actual process of loading the file or defining the function: those would raise ImportError.

There's probably not much you can do about a ModuleNotFoundError; you can either ignore it and not use the module you tried to import later in the code, or exit and fix your environment so that the module will be found.

According to the python docs:

The ImportError is raised when an import statement has trouble successfully importing the specified module. Typically, such a problem is due to an invalid or incorrect path, which will raise a ModuleNotFoundError in Python 3.6 and newer versions.

Related