Where to define exception classes, inside classes or on a higher level?

。_饼干妹妹 提交于 2020-01-02 01:05:16

问题


Should exception classes be part of the class which may throw them or should they exist on a higher level?

For example :

class Test
{
    public:
        class FooException: public ExceptionBase { };
        void functionThrowingFooException();
};

or

class FooException: public ExceptionBase { };
class Test
{
    public:
        void functionThrowingFooException();
};

(functionThrowingFooException() is the only function to ever throw a FooException)


回答1:


Exceptions really model error conditions. Are those specific to each class? What if you need to raise an exception from a free function?

If you go the route of providing different exception types for various problem states - analyze/list those error states, name exceptions after them, put whatever state-specific data into those exception types, derive from a subclass of std::exception, then declare in a separate header.




回答2:


I think it's all a matter of personnal taste (a form of coding convention, really).

I prefer to put them outside the class definition, but that's probably because that's how it's done in .NET's BCL.

Then again, if that exception is used only there... Is there any reason to throw an exception?



来源:https://stackoverflow.com/questions/4528362/where-to-define-exception-classes-inside-classes-or-on-a-higher-level

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!