#include
#include
class StupidClass
{
public:
~StupidClass()
{
// this is just asking for trouble!
throw std::runtime_error("this is stupid");
}
};
int main()
{
try
{
auto && sc = StupidClass();
throw std::runtime_error("something wicked this way comes");
}
catch(...) // catch all just used for demonstration purposes!
{
// I can't help you - code never gets here!
std::cerr << "handled error!" << std::endl;
}
}
#include <cassert>
#include <stdexcept>
#include <iostream>
class StupidClass
{
public:
void CleanUp()
{
// I'm a stupid function that always throws - duh!
dirty_ = false;
throw std::runtime_error("this is stupid");
}
~StupidClass()
{
// if this triggers class is being used wrong!
assert("your class is still dirty" && !dirty_);
try
{
// just in case the user of this class was dumb and didn't read
// the instructions on how to safely and correctly destroy me.
if(dirty_)
{
// if it fails all we can do is ignore (maybe log to log file)
CleanUp();
}
}
catch(...)
{
// Eeek, dragons! Sadly, we've had to ignore them.
assert("clean-up failed" && false);
}
}
public:
bool dirty_; // if set the class needs cleaning
};
int main()
{
try
{
auto && sc = StupidClass();
sc.CleanUp(); // errors but at least destructor won't terminate now
}
catch(...) // catch all just used for demonstration purposes!
{
std::cerr << "handled error!" << std::endl;
}
}
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)