Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling possible type of import errors

Tags:

python

I am trying to handle possible errors seen during import operations at the beginning of the execution of python program.

try:
    import sys
    import re
    import foobar
except ImportError as impErr:
    print("[Error]: Failed to import {}.".format(impErr.args[0]))
    sys.exit(1)

This code is working fine. However I am not confident that this is enough to catch the possible issues during import. For example , will this catch ModuleNotFoundError exception ?

exception ModuleNotFoundError A subclass of ImportError which is raised by import when a module could not be located. It is also raised when None is found in sys.modules.

New in version 3.6.

If just using ImportError is not enough, can someone please tell how to use OR condition to catch exception from ImportError and ModuleNotFoundError?

like image 351
monk Avatar asked Sep 01 '25 10:09

monk


2 Answers

try:
    import sys
    import re
    import foobar
except (ImportError, ModuleNotFoundError) as (impErr, mNFE):
    print("[Error]: Failed to import {}." etc...
    sys.exit(1)
like image 104
sveculis Avatar answered Sep 03 '25 00:09

sveculis


It is enough to use just ImportError because ModuleNotFoundError is a sub-class of ImportError, but if you want to do some extra stuff on ModuleNotFoundError you may want to use below code.

try:
    import sys
    import re
    import foobar
except ModuleNotFoundError as moduleErr:
    print("[Error]: Failed to import (Module Not Found) {}.".format(moduleErr.args[0]))
    sys.exit(1)
except ImportError as impErr:
    print("[Error]: Failed to import (Import Error) {}.".format(impErr.args[0]))
    sys.exit(1)
like image 37
furkanayd Avatar answered Sep 02 '25 23:09

furkanayd