Mixing metaclasses and exceptions

Steve Menard foo at bar.com
Tue Dec 28 03:44:23 CET 2004


In writing the next version of Jpype (Python to Java bridge), I have hot 
a rather unpleasant wall ... Hopefully it is I who is doing something 
wrong and i can be fixed ...

Since I am bridging Java classes and presenting them as Python classes, 
I decided to try to create a corresponding python class for every Jva 
classes accessed inside the python program. So far, everything is great 
.. until we get to exception handling.

Since I am creating classes, on the fly, I thought the easiest and most 
pythonic way to do it would be to create a metaclass. This is true also 
for the Java exception classes.

The problem arises when I try to raise one of those exception classes 
... it sems Python will not allow classes that have a custom metaclass 
to be raised as exceptions! Even though those classes derive from 
Exception! To illustrate, try the following snippet :

class mc(type) :
     pass

class foo(Exception, object) :
     __metaclass__ = mc
     pass

try :
     raise foo, 'ex'
except Exception, ex :
     print ex.__class__, ex


Note the above code has nothing to do with JPype. When I try to run the 
above, I get the following error :

exceptions.TypeError exceptions must be classes, instances, or strings 
(deprecated), not mc

Is there anything I can do to raise exception that have metaclasses? 
Maybe I can make my metaclass acceptable to "raise" somehow?

Thanks for any help anyone can provide.


Steve



More information about the Python-list mailing list