0

if you create an exception object on the heap and throw the pointer to that object, it will not be cleaned up.

Can someone help me how to implement this ?

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by Narue
0

Wait.. what? Do you want it to be cleaned up? Or are you trying to demonstrate how it's not cleaned up? I'm confused.

1

Technically it is cleaned up, unless you're on a platform that doesn't reclaim dynamic memory for a process when the process terminates. But if you mean the pointer is never deleted explicitly, that's easy enough. Just print something in the destructor, throw an unhandled exception, and watch the message never get printed:

#include <cstdlib>
#include <exception>
#include <iostream>

class SimpleException {
public:
    SimpleException() { std::cerr<<"Creating MyException object\n"; }
    ~SimpleException() { std::cerr<<"Destroying MyException object\n"; }
};

void unhandled_handler()
{
    std::cerr<<"Terminating due to unhandled exception\n";
    std::exit(EXIT_FAILURE);
}

#define CATCH_UNHANDLED 0 // Set to 1 to catch and delete

int main()
#if CATCH_UNHANDLED
try
#endif
{
    std::set_terminate(unhandled_handler);
    throw new SimpleException();
}
#if CATCH_UNHANDLED
catch (const SimpleException* pex) {
    delete pex;
}
#endif
Votes + Comments
No _jsw variables... This deserves +ve rep.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.