const exceptions



 DEVELOP > c-Plus-Plus > const exceptions

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
Topic: DEVELOP > c-Plus-Plus
User: ""
Date: 05 Sep 2006 05:10:11 PM
Object: const exceptions
Hi, just wondering if anybody can answer the following question as it
doesn't seem to be anywhere in the C++ spec.
What will print from the following statement? (note the order of the
catch statements):
void func(void)
{
try
{
const foo f1;
throw f1;
}
catch(foo &)
{
cout << "foo &" << endl;
}
catch(const foo &)
{
cout << "const foo &" << endl;
}
catch(...)
{
cout << "..." << endl;
}
}
.

User: "Thomas J. Gritzan"

Title: Re: const exceptions 05 Sep 2006 05:30:42 PM
schrieb:

Hi, just wondering if anybody can answer the following question as it
doesn't seem to be anywhere in the C++ spec.

The compiler can.

What will print from the following statement? (note the order of the
catch statements):

void func(void)
{
try
{
const foo f1;
throw f1;
}

Since classes are thrown by value (copied), the const qualifier doesn't
affect the thrown object. So the body of catch(foo&) will run.
g++ also gives this warning:
$ g++ throw.cpp
throw.cpp: In function 'int main()':
throw.cpp:20: warning: exception of type 'foo' will be caught
throw.cpp:16: warning: by earlier handler for 'foo'
And the output:
$ ./a.out
foo &
--
Thomas
http://www.netmeister.org/news/learn2quote.html
.
User: "mlimber"

Title: Re: const exceptions 06 Sep 2006 10:58:41 AM
Thomas J. Gritzan wrote:

aspestrand@gmail.com schrieb:

Hi, just wondering if anybody can answer the following question as it
doesn't seem to be anywhere in the C++ spec.


The compiler can.

What will print from the following statement? (note the order of the
catch statements):

void func(void)

Abomination! (Cf.
<http://groups.google.com/group/comp.lang.c++/msg/895f1f98c4488dda>.)

{
try
{
const foo f1;
throw f1;
}


Since classes are thrown by value (copied), the const qualifier doesn't
affect the thrown object. So the body of catch(foo&) will run.

g++ also gives this warning:

$ g++ throw.cpp
throw.cpp: In function 'int main()':
throw.cpp:20: warning: exception of type 'foo' will be caught
throw.cpp:16: warning: by earlier handler for 'foo'

And the output:

$ ./a.out
foo &

I'd add to this that, when you can (which is almost always), you should
catch a *const* reference (see
<http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.7> and
<http://www.parashift.com/c++-faq-lite/const-correctness.html>).
Cheers! --M
.



  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER