2

I have following code sample,

class Outer:
    class InnerException(Exception): pass
    def raise_inner(self):
        raise Outer.InnerException()
    def call_raise(self):
        try:
            self.raise_inner()
        except Outer.InnerException as e:
            print "Handle me"

 Outer().call_raise()

What I wish to do is instead of using Outer.InnerException just use InnerException inside the Outer class, in short something like this

class Outer:
    class InnerException(Exception): pass

    #InnerException = Outer.InnerException .. something like this, create some alias

    def raise_inner(self):
        raise InnerException()
    def call_raise(self):
        try:
            self.raise_inner()
        except InnerException as e:
            print "Handle me"

 Outer().call_raise()
Rod
  • 48,232
  • 3
  • 34
  • 52
Nikhil Rupanawar
  • 3,771
  • 9
  • 32
  • 49

3 Answers3

3

You can't just refer to things declared in class scope with a name (unless you are doing so also in class scope).

Either do:

class Outer:
    class InnerException(Exception): pass
    def raise_inner(self):
        raise self.InnerException()

or

class InnerException(Exception): pass
class Outer:
    def raise_inner(self):
        raise InnerException()
Marcin
  • 46,667
  • 17
  • 117
  • 197
1

The name InnerException is looked up at the time the method is called, so the exception name is a non-local value. You could write

class Outer:
    class InnerException(Exception): pass

    # methods

InnerException = Outer.InnerException

but that mostly defeats the purpose of defining InnerException inside the class Outer in the first place. You could just as easily write

class Outer:
    # methods

class InnerException(Exception): pass

because both make the name InnerException refer to an exception in the module scope (although in the second case, InnerException is no longer a class attribute of Outer, of course).

chepner
  • 446,329
  • 63
  • 468
  • 610
1

I suppose you could do something like this to define it within each function's enclosing scope, which creates a local variable that's an alias for it:

class Outer:
    class InnerException(Exception): pass
    def raise_inner(self, InnerException=InnerException):
        raise InnerException()
    def call_raise(self, InnerException=InnerException):
        try:
            self.raise_inner()
        except InnerException as e:
            print "Handle me"

Outer().call_raise()
martineau
  • 112,593
  • 23
  • 157
  • 280