14

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)

rve
  • 5,897
  • 3
  • 40
  • 64
  • 1
    I guess this depends on whether or not the exceptions will be thrown outside of the class or not. I've never actually used C++ exceptions though. – Falmarri Dec 24 '10 at 21:18
  • I think consideration on where to throw (how many levels) also needs to be debated during the design. In the first example, the scope of the exception class is Test class. So any other class object cannot "decode" the exception. So it is pure design issue. I would go with option 2. – kumar_m_kiran Dec 25 '10 at 12:08
  • @kumar_m_kiran: Other class objects can decode the exception because it is public. – rve Dec 25 '10 at 12:25
  • @rev: Not really, Just the class begin public will not suffice. Think about it,when the exception object is thrown, the callers catch block (called from another class) will not know the Test obj. So being public will not help. – kumar_m_kiran Dec 25 '10 at 12:33
  • @kumar_m_kiran: You can do `catch(Test::FooException&)` or you can do `catch(FooException&)`... – rve Dec 25 '10 at 12:43

2 Answers2

4

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.

Community
  • 1
  • 1
Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
  • 1
    why declare them in a separate header? – rve Dec 25 '10 at 06:12
  • I thought about it and tried some different ways of doing things and it makes more sense (in my case at least) to put them in a separate header and not make them part of a class so I am accepting this answer. – rve Dec 28 '10 at 09:37
  • Late response, sorry. I'd prefer a separate header simply because one can ignore custom exception types (provided they are descendants of `std::exception`) in general case, but can explicitly include that header and deal with custom exceptions if necessary. – Nikolai Fetissov Dec 30 '10 at 20:53
0

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?

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111