Computer >> Computer tutorials >  >> Programming >> Python

How to catch ImportError Exception in Python?


ImportError is raised when a module, or member of a module, cannot be imported. There are a two conditions where an ImportError might be raised.

  • If a module does not exist.

Example

import sys
try:
    from exception import myexception
except Exception as e:
    print e
    print sys.exc_type

Output

No module named exception
<type 'exceptions.ImportError'>
  • If from X import Y is used and Y cannot be found inside the module X, an ImportError is raised.

Example

 import sys
 try:
    from time import datetime
 except Exception as e:
    print e
    print sys.exc_type

OUTPUT

 cannot import name datetime
<type 'exceptions.ImportError'>