views:

123

answers:

4

Hi All

I have a customized exception class. say class CustomExcep{};

My Application is a middleware made of C++. It is a webservice which is used for the communication between Java based web Front-end and the DCE Backend.

whenever the DCE Backend is not running or down due to some core dumps, the application throws the CustomExcep.

It's like this.

CustomExcep * exc = new CustomExcep(); throw exc;

I am unable to use the stack memory for this as it leads to some run-time exceptions.

I need a solution to clear the memory used by this CustomException. Can we use Templates for this purpose?

Any help would be appreciated. Thanks in Advance.

A: 

When you catch the exception you need to delete it.

Douglas Leeder
A: 

You should be able to use the stack for this. If you aren't, may be that's the real problem you need to address.

I wouldn't recommend creating an exception on heap at all.

Frederick
A: 

As Frederick mentioned, you should probably go for a stack based solution. If you're worried about the cost (or side effects) of copying and not worried about allocation failures, you can allocate memory within your exception class and store it in a smart-pointer member, thereby making copying a cheap and side effect free procedure, and your memory will be release automatically.

On Freund
Hi On Freund,Thanks for the advice. But my trouble is that i cannot use stack memory as the side effects is huge. is that possible to use templates for this in any way, i mean to throw an exception from inside a template class. Will that work. Sorry if my question sounds silly, i'm newbie here.
ilan
I don't see why you can't use stack memory for the exception class and have it hold a member that is allocated on the heap. If the exception class simply holds a (smart) pointer, there shouldn't be any side effects.
On Freund
+1  A: 

Pre allocate the exception using the static keyword.

static const CustomExcep e;
throw e;

Microsoft's VC++ implementation of the "new"-operator uses this technique. By using the static keyword only one exception will be created throughout the applications lifetime, and then reused in every call. That way you don't have to worry about delete.

There are further complications of using other methods when it comes to exceptions because of how they are handled internally. Generally, new should be avoided with exceptions. I'll come back and explain further if I have time.

Zen