Reputation: 29156
I have a particular exception that can occur only inside the class Foo
Would it be good to use a inner exception class as below:
class Foo:
class FooError(Exception):
pass
def bar(self):
raise self.FooError('omg')
Or it is better to put FooError
outside from Foo
?
class FooError(Exception):
pass
class Foo:
def bar(self):
raise FooError('omg')
Upvotes: 5
Views: 936
Reputation: 10193
Put it outside, because of export rules. This exception is only raised inside the class, but it might (and probably will) bubble to other parts of the code, so other modules may want to catch it.
If the exception is outside the class, you can choose to export only the exception. If the exception is inside the class, you have to either export the entire class with the exception, or use something like __all__ = [Foo.FooError, ...]
, basically mimicking an outside exception.
If the exception was only ever raised and caught inside the class, it might make sense, but I still don't consider it idiomatic.
Upvotes: 7