Re: need argument for try catch blocks
"Edek" <edek.pieITAKNIECZYTAM@gmail.com>
Is it possible to do anything which may throw during stack unwind? I
always thought that was UB.
Depends. If you use the standard library, it states that you'll have UB
if your type T emits an exception from a destructor.
In general that is not UB, but a double exception will end up in
terminate(). And a throwing destructor can leave behind memory leaks,
incosistencies and much other stuff you do not want. for that reason it
is a strong guideline that destructors must be nothrow. Those ignoring
it are likely in peril regardless other stuff.
Yes, that I know. Actually, what I mean is this
struct Deleter {
... holds a DB connection
~Deleter () {
try {
.. whatever that may throw
} catch (...) {} // does not emit. But is it legal? }
Yes, that is perfectly legal. The standard tays that if a dtor called in the
stach unwinding *exits* through an exception, then terminate() is called. So
you are supposed to catch and swallow them. (see section 15.2 or .3)
Some libraries use uncaught_exception() in dtors and only swallow if it is
true. IIRC that is not a surefire way and the return value is not in exact
match with that intent, but I forgot the details. But as alrady mentoned,
emitting dtor has problems in other contexts too, so the above code makes
general sense, if anything not nothrow() is actually called.
The only realistic bad case I recall if for CFile used as output and not .
Close()-d in MFC 4.2 (might got fixed for more current versions).
int some {
scoped_ptr<Deleter> del(new Deleter(openDbConnection()) );
// ... here something throws
// destructor throws and catches
// is this UB?
}
Is this UB or not? I've always thought it is.
With the try-and swallow it is okay.
for the standard library the applicable part is at 17.4.3.6 bullet 4
In particular, the effects are undefined in the following cases: ...
- if any replacement function or handler function or destructor operation
throws an exception, unless specifically allowed in the applicable Required
behavior paragraph.
This only applies to exceptions actually escaping.