Sunday, April 24, 2016

Python exceptions

When writing Python code it's import to trap errors :) And MMA does this, fairly well.

But, I just had some fun with the plugin loader. I kept getting a weird error message which didn't make a lot sense. After a bit (well, actually quite a bit!) of head scratching I finally figured it out.

In the module I have a bit of code which looked a bit like this:

        e = importlib.import_module(modName, package=None)
    except ImportError:
         error( ... report error ... )

this was meant to trap/report a problem loading the plugin module. If the module just didn't exist or was unreadable it worked fine.

But, what if the module was there and there was an error in it which caused a problem when loading? If it was something dumb like too many '(' or ')'s python reports the appropriate error as a crash. Okay, that's probably just fine. Writers of plugins should make sure that they work!

But, what if the module being loaded has a "import xxx" line? Well, since we're catching import errors, we catch it. I don't think we can set up a try/except which only works a one level.

The solution is simply to change our code to:

        e = importlib.import_module(modName, package=None)
    except ImportError, err:
        error("Plugin: Error loading module '%s'. Python is reporting '%s'. "
               "Most likely there is an Import statement in the module which is not working."% (modName, str(err)))

and now MMA reports a more useful message.

No comments:

Post a Comment

Mea Culpa

Isn't it just plain annoying when you end up wasting most of an afternoon trying to find a bug in your code when there is no bug? Just h...