I'd like to nest an Exception subclass within a class of my own, like so:
class Foo(object):
def bar(self):
#does something that raises MyException
class MyException(Exception):
pass
This way, I only have to import Foo (and not MyException) when calling bar() from another module. But what I have below doesn't work:
from foo_module import Foo
foo = Foo()
try:
foo.bar()
except Foo.MyException as e:
print e
Python gives this error:
type object 'Foo' has no attribute 'MyException'
Is there a way to do this?
Given the contents of t.py
of:
class Foo():
def RaiseBar(self):
raise Foo.Bar("hi")
class Bar(Exception):
pass
And running this on the python terminal:
>>> import t
>>> x = t.Foo()
>>> try:
... x.RaiseBar()
... except t.Foo.Bar as e:
... print e
...
hi
Is not this exactly what you were looking for?
Not sure what you did wrong with yours, I suggest you re-examine the code more closely.
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