Exception handling - is it good the clear up resources before every throw statement ?

Hello forum,

I have a class that contains several pointer type variables and std::vector that contain pointer variable types. Exception can be thrown anywhere inside the member function of the class as long as logic supports.

Is it not a good idea to clean up the resources before throwing the exception ?

I also have my own exception class related to the class to give more specific information about the exception. The following snippet will make more sense, I guess.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

class B;

class A
{
   public:
     A();
     ~A();

     void init();

   private:
     
     void cleanup();

     std::vector<B*> bVector; 

};

class AException : public std::exception
{
   public:
      AException() : msg("Error in the class A");
      AException(const std::string &msgInit) : msg("Error in the class A: " + msgInit) {}
   private:
     std::string msg;
};


Now if The programmer throw an exception of the type we have just created inside the A::init() function, does she need to call the A::cleanup() function before throwing the exception ?

The init() function definition does not contain any try/catch block. It throws the exception if certain condition is not met.
Is it not a good idea to clean up the resources before throwing the exception ?

Not really.

As long as cleanup() is called by your class' destructor then all clean up should happen automatically, as intended. Which fits in with the whole RAII ethos.

Andy
it should happen automatically in the destructor.

you should use c++11 automatic memory management classes like std::shared_ptr and std::unique_ptr for handling memory


if the objects in the vector may be owned by other pointers in your code as well:
std::vector<std::shared_ptr<B>> bVector;

if they should only be available in this vector
std::vector<std::unique_ptr<B>> bVector;
Thanks for the hint !

What if the programmer has to throw excepption inside the constructor while creation of the object. In that case the destructor will never be called and some resources might already have been created using new. Will it taken care of if I use unique_ptr as well or I have to clean up the resources explicitly inside the catch handler?
Will it taken care of if I use unique_ptr as well ...

Yes.

or I have to clean up the resources explicitly inside the catch handler?

No

(If you're constructing your object inside a try block you won't even get the chance to do so as it won't be accessible in any of the associated catch blocks.)

Andy
Last edited on
Topic archived. No new replies allowed.