jayapal said:
Hi ,
I am using the NEW operator to allocate the memory in many places of
my code.But I am not doing any error hadling or exception handling.Can
any one suggests me how to do exception handling, which code part I
have to add to do the exception handling
Exception handling is done by adding try blocks, catch handlers, and throw
statements to your code. Where to put them depends on what you want to
achieve. Some throw statements may allready be in your code hidden in calls
to library functions that might throw.
The interaction of try-throw-catch and manually managed pointers is tricky.
Since every new() is to be matched with one and only one corresponding
delete() along _each execution path_, try-throw-catch makes manual pointer
management much harder. Any line that could throw can divert the flow
control to some catch handler; any pointer that undergoes stack unwinding
may leak memory. E.g.:
try {
some_type * some_ptr ( new some_type ( some parameters ) );
some_ptr->mem_fct(); // if this line throws, delete will not be called.
delete some_ptr;
}
catch ( ... ) {
// here the some_ptr object is irretrievably lost.
// memory has leaked
}
Note that it is very hard to tell which lines may throw. In particular when
templates enter the picture, the type "some_type" in the above snippet may
be a user provided type. In that case, all bets are off as to whether
mem_fct() could throw. The only safe attitude is: each line can throw and
flow control may go some ((possibly unknown) place at any given moment.
Various idioms can be used to ensure that every new() is matched with a
corresponding delete(). You may want to read up on RAII and on smart
pointers.
Best
Kai-Uwe Bux