Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest custom exception class within class? (Python) [closed]

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?

like image 688
XåpplI'-I0llwlg'I - Avatar asked Feb 21 '23 17:02

XåpplI'-I0llwlg'I -


1 Answers

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.

like image 102
gahooa Avatar answered Mar 03 '23 06:03

gahooa