Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

exception

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)

like image 494
rve Avatar asked Dec 24 '10 21:12

rve


1 Answers

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.

like image 190
Nikolai Fetissov Avatar answered Oct 05 '22 23:10

Nikolai Fetissov