Understanding exceptions specifications and the operation of unexpected()
Below is a bare-bones implementation of a structure I've been working
on to test my understanding of exception specifications and how
violations are handled via the mechanism that calls std::unexpected().
It compiles under Comeau C++ 4.3.10.1 (online) and gcc 3.4.4 (Cygwin),
and runs as I would expect under that latter. It uses the "Resource
Allocation Is Initialization" model to handle setting of the custom
unexpected_handler and ultimately catches bad_exception in main (see
output).
What I'm trying to make sense of, however, is what is happening behind
the scenes between the initial violation in g() with the subsequent
call of unexpected() and invocation of the custom handler udu_handler,
and the ultimate delivery of bad_exception to main.
Experimentation shows that the generic throw in the udu_handler is
still throwing the original f_err generated in f(). (Adding an
exception specification throw(f_err) to the definition of udu_handler
appears to prove this). Clearly this is handled somewhere and 'traded'
for bad_exception which the calling code in main is left to handle.
(continued after example...)
#include <exception>
#include <iostream>
struct g_err { };
struct f_err { };
class RAII_set_handler {
std::unexpected_handler old_uh;
public:
RAII_set_handler(std::unexpected_handler new_uh) {
old_uh = std::set_unexpected(new_uh);
}
~RAII_set_handler() { std::set_unexpected(old_uh); }
};
void udu_handler() { // user-defined unexpected handler
std::cout << "in udu_handler\n";
throw; // line 18
}
void f() throw(f_err) { throw f_err(); }
void g() throw(g_err, std::bad_exception) { f(); }
int main()
{
RAII_set_handler uh(&udu_handler);
try {
g();
} catch (g_err) {
std::cout << "g_err\n";
} catch (f_err) {
std::cout << "f_err\n";
} catch (std::bad_exception) {
std::cout << "bad_exception\n";
}
return 0;
}
/* output:
* in udu_handler
* bad_exception
*/
What I don't understand, however, is the necessity of the throw
statement in udu_handler and why, since we are not in a catch
statement, f_err doesn't just propagate through in any case. Removing
it apparently causes a termination much as if the user-defined handler
hadn't be set in the first place.
Unfortunately, on my system at present, I don't have access to the
definition of unexpected(), just its declaration in <exception>. Any
help in trying to make sense of what is actually going on in, and
around, the custom handler here would be very welcome. As usual, it
doesn't feel enough just to know how to write (hopefully) working
code, without having a sense of what's actually going on back stage.
PB
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]