ilan
ilan

Reputation: 59

How to clear the memory allocated for Customized Exception

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.

Upvotes: 0

Views: 230

Answers (4)

Zen
Zen

Reputation: 1978

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.

Upvotes: 1

On Freund
On Freund

Reputation: 4436

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.

Upvotes: 0

G S
G S

Reputation: 36818

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.

Upvotes: 0

Douglas Leeder
Douglas Leeder

Reputation: 53310

When you catch the exception you need to delete it.

Upvotes: 0

Related Questions