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
  • 52,748
  • 3
  • 38
  • 55
Nikhil Rupanawar
  • 4,061
  • 10
  • 35
  • 51

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
  • 48,559
  • 18
  • 128
  • 201
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
  • 497,756
  • 71
  • 530
  • 681
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
  • 119,623
  • 25
  • 170
  • 301