If exceptions are always fatal, making use of them in Python is easy
# moduleB.py
import moduleC
But evaluating an exception requires more than just it's type, we often need to determine where an exception came from
# moduleA.py
try:
import moduleB
except ImportError as e:
print e
if str(e) == "No module named moduleB":
pass
else:
raise
In开发者_运维问答 some projects this pattern results in a lot of code that is not easy to read. Is this the best way to ensure that I'm catching a local exception? I would like to be able write
import moduleB else pass
Sorry, but the example you posted is the canonical Way Of Doing It. Python doesn't have any syntax for catching the exception raised by the import
statement but not by something below it.
Just a small warning, though: str(e)
can cause unicode errors if e
's message is unicode. You can fix that by using repr(e)
.
No, don't try to analyse the error string. You can log the exception for debugging if you want, but if it's "import if you can", then this will suffice:
try:
import foo
except ImportError:
pass # or foo = None or whatever
In your specific case, parsing the string is the only viable solution, but note that you don't need to do it: what is the difference if the moduleB
or if it is a module imported by the moduleB
not to be found?
If you are throwing custom exceptions, you can provide additional information when you raise them:
raise Exception(12) # 12 is the error code
and then get it through the args
property:
if e.args[0] == 12:
handle()
A better way may be to subclass Exception
and provide your own properties (for example error_code
or module_name
).
try:
import moduleB
except ImportError:
pass
This ought to be both sufficient and succinct enough.
精彩评论