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.
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.
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.)