Connecting Tech Pros Worldwide Help | Site Map

const exceptions

  #1  
Old September 5th, 2006, 10:55 PM
aspestrand@gmail.com
Guest
 
Posts: n/a
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;
}
}

  #2  
Old September 5th, 2006, 11:25 PM
Thomas J. Gritzan
Guest
 
Posts: n/a

re: const exceptions


aspestrand@gmail.com schrieb:
Quote:
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.
Quote:
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
  #3  
Old September 6th, 2006, 04:45 PM
mlimber
Guest
 
Posts: n/a

re: const exceptions


Thomas J. Gritzan wrote:
Quote:
aspestrand@gmail.com schrieb:
Quote:
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.
>
Quote:
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>.)
Quote:
Quote:
{
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.7and
<http://www.parashift.com/c++-faq-lite/const-correctness.html>).

Cheers! --M

Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
exceptions Josefo answers 10 September 23rd, 2006 08:15 AM
Problem with exceptions, templates and pure virtual functions Dmitry Prokoptsev answers 3 July 8th, 2006 08:55 PM
String literal and const al answers 7 November 14th, 2005 12:30 AM
Exceptions Eric answers 10 July 22nd, 2005 07:47 AM