This is kind of concept question.
Lets assume that we have some code base that works with hardware from high level and whole error handling mechanism is implemented by exceptions. Lets assume that we are opening/closing some valve(s). As long this hardware operation have finalizing procedure we need to use RAII conception. So some foo() procedure could look like this:
class Valve()
{
public:
Valve()
{
// open valve
}
~Valve()
{
// close valve
// Potential exception here
}
private:
// valve internal stuff
}
void foo()
{
try
{
Valve v;
bar1(v); // <--- throws something
} catch(...)
{
// report error and exit
// it's guaranteed that valve destructor will be called
}
}
This piece of code looks nice, but how we can manage errors that could happen during valve closing. Exception couldn't leave destructor. The only way I see is keeping error in some error storage, like this:
Valve::~Valve()
{
try
{
// close valve
} catch(...)
{
errorStorage.Add(...);
}
}
But this approach looks ugly. Are there any ideas how to deal in this situation? Of course one way is not using of the exceptions at all, but use return code approach and some cleanup action (with goto in case of error).
UP: Originally I wanted to avoid this kind of logic duplication:
void foo()
{
try
{
Valve v;
v.open(); // <- could throw
bar1(v); // <- could throw
v.close(); // <- could throw
} catch(...)
{
if(v.opened())
v.close(); // kind of logic duplication
}
}