Custom Nest exception class inside a class? (Python)

I would like to nest a subclass of Exception in my own class, for example:

class Foo(object):

    def bar(self):
        #does something that raises MyException

    class MyException(Exception):
        pass

Thus, I need to import Foo (and not MyException) when calling bar () from another module. But what I have below does not work:

from foo_module import Foo

foo = Foo()

try:
    foo.bar()
except Foo.MyException as e:
    print e

Python gives this error:

The object type "Foo" does not have the attribute "MyException"

Is there any way to do this?

+3
source share
1 answer

Given the contents t.pyof:

class Foo():
  def RaiseBar(self):
    raise Foo.Bar("hi")
  class Bar(Exception):
    pass

And running this on a python terminal:

>>> import t
>>> x = t.Foo()
>>> try:
...     x.RaiseBar()
... except t.Foo.Bar as e:
...     print e
... 
hi

Isn't that what you were looking for?

Not sure what you did wrong with yours, I suggest you study the code more carefully.

+6
source

All Articles