try except ImportError failing to catch error!

Peter Hansen peter at
Wed Sep 18 09:52:33 EDT 2002

Ben Gerblich wrote:
> I am importing all module files in the CWD. This part works fine.
> I want to add the functionality to catch the error if there is a
> typo in the imported module file. The following does not catch
> the error!
> try:
>    self.userDefs[file[:-3]]['class'] = __import__(file[:-3])
> except ImportError, e:
>    print 'cant do it', e
> I still get the runtime error:
> TypeError: line() takes exactly 5 arguments (6 given)

That's not an import error, so your exception handler won't
catch it.  If you want to catch *any* error in the imported
module, you'll have to do "except Exception, e" instead.
Unfortunately, then you'll also have ImportErrors in the mix,
so you won't know if the module could be found but had its
own error, or if the call to __import__ failed...

Also, you won't know whether perhaps the file[:-3] expression
failed, or any of the other stuff that might fail in that
import line.

> And is there a way for my handler routine to return the line-number of 
> the imported module file that caused the error?

Look into the traceback standard module.

I don't understand why you want to intercept these exceptions
anyway.  If you want to catch the error, *and* the line number,
and print it, why don't you want Python to show you where
the problem came from?  Maybe there's a better approach than
what you've selected so far...


More information about the Python-list mailing list