简体   繁体   中英

inner or outer exception class in Python?

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')

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM