Boost logo

Boost :

From: Bill Seymour (bill-at-the-office_at_[hidden])
Date: 2002-08-14 13:59:21


>
> Quiz: what does this program do?
>
> #include <iostream>
>
> struct X
> {
> };
>
> struct Y: public X
> {
> };
>
> void f()
> {
> try
> {
> throw Y();
> }
> catch(X)
> {
> throw;
> }
> }
>
> int main()
> {
> try
> {
> f();
> }
> catch(Y)
> {
> std::cout << "Caught an Y!\n";
> }
> }
>

Unsurprisingly, it writes "Caught an Y!\n" as written because
"throw;" just rethrows the current exception, whatever it is;
and when I change the catch in f() to catch(X x) { throw x; },
I get "abnormal program termination" because the exception gets
sliced. (I'm not sure why I say "unsurprisingly" because I
don't see either of those behaviors explicitly mentioned
in clause 15 of the Standard. Is it there somewhere and I
just missed it?)

What did surprise me is that, when I catch the exception
in f() by either const or non-const reference, the exception
still gets sliced. I added a catch(X) block after the
catch(Y) in main() and the "abnormal program termination"
became "Caught an X!\n", so slicing really does explain it.

It seems to me that slicing when catching by reference
is a bug in my implementation; but I can't cite anything
in the Standard to support that. 8-(

--Bill Seymour


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk