Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to catch ImportError Exception in Python?

If I run this line of code, I get an error

from time import datetime

or if I run the following code also, I get an error

import exception

How do I catch such exceptions and know their types?


1 Answer
Rajendra Dharmkar

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.

  1. If a module does not exist.
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'>
  1. If from X import Y is used and Y cannot be found inside the module X, an ImportError is raised.
 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'>
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.