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
?
try:
import sys
import re
import foobar
except (ImportError, ModuleNotFoundError) as (impErr, mNFE):
print("[Error]: Failed to import {}." etc...
sys.exit(1)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With