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 ?
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.
to demonstrate that is not clean up
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
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.