Where to define exception classes, inside classes or on a higher level?
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:
开发者_StackOverflow中文版 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
)
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.
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?
精彩评论