I am trying to learn error trapping using the C++ commands try, throw, and catch.
The problem I seem to be encountering is when I use new to declare an array. When the program throws an exception, don't I need to delete those arrays to prevent a memory leak? I am thinking yes. But, when I try to compile code with the delete commands in the catch, I get a variable out of scope error from the compiler.
I am doing something like this:
int function ()
{
try {
string * files = new string[dirsize];
code;
if (something bad happens)
throw ("error");
more code;
delete[] files;
return 1;
} // closing try section
catch (const char *msg)
{
delete[] files; // this is where I get the compiler error
cout << msg;
} // end catch
} //close function
Now, I know I could put the delete command here, as:
if (something bad happens) {
delete[] files;
throw ("error");
}
But, doing it this way would seem to defeat the purpose of the throw command. I could just as easily structure the program with and if{}else{} combination and get a similar outcome without using the try, throw, catch commands.
So, I feel that I am missing something about the purpose, or proper use, of try, throw and catch.
Yes, I know I could avoid some of this by using vector, or some other container, but that would still not educate me about try, throw and catch.
What am I missing?
Thanks.