问题
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