Skip to main content
gamedev.net
🔒 Locked

Exception handling

Started by Wavarian 0 replies 250+ views
Original Post
Wavarian
Wavarian
Lets say I have a procedure set up like so:
  
void proc(){
   Obj *temp = NULL;

   temp = new Obj[50];
   // Do something with temp array here

   delete[] temp;
}
  
How would you go about clearing the allocated memory if an exception is encountered? I hear the use of try() catch() and throw are pretty ''slow'' (for lack of a better word right now), and should be only used where needed. First solution:
  
void proc(){
   Obj *temp = NULL;

   temp = new Obj[50];
   // Do something with temp array here

   if(exceptionEncountered){
      delete[] temp;
      throw 1;
   }
   delete[] temp;
}
  
Second solution:
  
   Obj *temp = NULL;
   
   try{
      temp = new Obj[50];
      // Do something with temp array here

      if(exceptionEncountered)
         throw 1;

      delete[] temp;
   }
   catch(...){
      delete[] temp;
      throw;
   }
  
your solution? I don''t know, but I haven''t found a good use of try, catch and throw in my coding projects. I like being able to know if my variables are valid etc, and handling them in my own way, but I hear that those methods are old and reduce readability. So I''m trying to work exception handling into my code, but so far, it''s just made it a little more cluttered (ie in the 2nd scenario, i havent tried the first one yet). Any ideas on what I can read or things i could consider when handling exceptions within a library?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.