"Jacek Dziedzic" <jacek@__N_O_S_P_A_M__janowo.net> wrote in message news:<bu**********@korweta.task.gda.pl>...
Hi!
I'm trying to make friends with exceptions. I think I'm doing well,
there is
one thing that bothers me, however. If an object is declared within a try
block, it gets destroyed on exception, because then we're into the catch
block and out of the try block, right? How can I sense in the destructor
that we're in the middle of processing an exception (and hence take
appropriate action, like not destroying the object if some EInternalError
exception is being processed).
try {
myclass myinstance;
myinstance.DoSomethingThatCausesAnException();
}
catch(...) {
cout << "Exception" << endl;
};
myclass::~myclass() {
// take care of destroying the object, but not if we're in the middle
// of processing EInternalError, because the object is now corrupt.
// But how to find out?
};
TIA,
- J.
Your object gets destroyed whether it's in the try block or not:
void F()
{
myclass x;
try {
x.DoSomethingThatCausesAnException();
}
catch (...) {
}
}
If your object is corrupted such that it can't be destroyed, you've
got a problem whether you're using exceptions or not.
void G()
{
myclass x;
x.DoSomethingThatCausesCorruption();
}
By "corrupted" I mean your object has gotten into a state that you
didn't anticipate or account for -- in other words, you've got a bug.
You need to fix the bug, not throw an exception. If this isn't what
you mean by corruption, then you don't really have a problem -- the
object should satisfy its invariants and should be destructible.
Meaning that myclass::DoAnything() should leave the object
destructible regardless of whether it returns normally or throws an
exception.
Bugs occur when your program behaves incorrectly; the proper response
is to fix the bug. Exceptions, on the other hand, are all about
letting your program continue execution; when an exception is thrown
in both your example and mine, the program will go on executing -- the
object gets destroyed, the function returns, etc.
To answer your question, there is a function called
std::uncaught_exception() which returns true between the time when an
exception is thrown and when it is caught. However, it's not as useful
as you might think. For example, it won't solve the problem you've
described, because the problem you've described is a bug, and calling
std::uncaught_exception() won't fix the bug.
Not to mention that I'm unaware of any compiler that actually
implements std::uncaught_exception()...
Note that if you call std::uncaught_exception() in the destructor in
your example, it will return true; in my example it would return
false.
Bob