473,395 Members | 1,568 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

exception and polymorphism problem

Hi I have this code:

class Exception : public exception
{
public:
Exception(string m="exception!") : msg(m) {}
~Exception() throw() {}
const char* what() { return msg.c_str(); }

private:
string msg;
};

int main()
{
try
{
throw Exception();
}
catch(exception e)
{
cout << e.what() << endl;
}

return 0;
}

when I run it I don't have print out my message "exception!" but
St9exception

why?

May 16 '07 #1
12 2146
On 16 Maj, 13:01, josh <xdevel1...@gmail.comwrote:
Hi I have this code:

class Exception : public exception
{
public:
Exception(string m="exception!") : msg(m) {}
~Exception() throw() {}
const char* what() { return msg.c_str(); }

private:
string msg;

};

int main()
{
try
{
throw Exception();
}
catch(exception e)
{
cout << e.what() << endl;
}

return 0;

}

when I run it I don't have print out my message "exception!" but
St9exception
Because you catch the exception by value, so you copy-construct a new
std::exception from the Exception that was thrown, catch the exception
by reference instead and it will work:

catch (exception& e)

--
Erik Wikström

May 16 '07 #2
On 5ÔÂ16ÈÕ, ÏÂÎç7ʱ01·Ö, josh <xdevel1...@gmail.comwrote:
Hi I have this code:

class Exception : public exception
{
public:
Exception(string m="exception!") : msg(m) {}
~Exception() throw() {}
const char* what() { return msg.c_str(); }

private:
string msg;

};

int main()
{
try
{
throw Exception();
An exception object is always created at the throw point.We reference
it as "temp" here.
}
catch(exception e)
The exception declaration of a catch clause behaves very much like a
parameter declaration. Here, e is another object of type exception
(Not Exception) that initialized by the "temp" of type Exception.
{
cout << e.what() << endl;
So, here, the e.what() refers to the what() member function of class
Exception, but not class exception.
}

return 0;

}

when I run it I don't have print out my message "exception!" but
St9exception

why?

May 16 '07 #3
On 16 Mag, 13:04, Erik Wikström <eri...@student.chalmers.sewrote:
On 16 Maj, 13:01, josh <xdevel1...@gmail.comwrote:
Hi I have this code:
class Exception : public exception
{
public:
Exception(string m="exception!") : msg(m) {}
~Exception() throw() {}
const char* what() { return msg.c_str(); }
private:
string msg;
};
int main()
{
try
{
throw Exception();
}
catch(exception e)
{
cout << e.what() << endl;
}
return 0;
}
when I run it I don't have print out my message "exception!" but
St9exception

Because you catch the exception by value, so you copy-construct a new
std::exception from the Exception that was thrown, catch the exception
by reference instead and it will work:

catch (exception& e)

--
Erik Wikström
yes I've forgotten that...... so it print 9Exception but not
my msg string may be I didn't override the right what() ?

P.S.
I try to read the source of exception.h and exception.cpp but in my
gcc source I didn't find it!
where are them?

May 16 '07 #4
josh wrote:
>
yes I've forgotten that...... so it print 9Exception but not
my msg string may be I didn't override the right what() ?
no, you did. the problem, as Eric said, is that if you don't put the
reference a new std::exception is created by copy-constructor. And for
the standard exception the what behaves differently that for your class.
P.S.
I try to read the source of exception.h and exception.cpp but in my
gcc source I didn't find it!
where are them?
it depends. For me, /usr/include/c++/4.1.2/exception

Regards,

Zeppe
May 16 '07 #5
On 16 Mag, 13:49, Zeppe <zeppe@.remove.all.this.long.comment.email.it>
wrote:
josh wrote:
yes I've forgotten that...... so it print 9Exception but not
my msg string may be I didn't override the right what() ?

no, you did. the problem, as Eric said, is that if you don't put the
reference a new std::exception is created by copy-constructor. And for
the standard exception the what behaves differently that for your class.
P.S.
I try to read the source of exception.h and exception.cpp but in my
gcc source I didn't find it!
where are them?

it depends. For me, /usr/include/c++/4.1.2/exception

Regards,

Zeppe
I do it but still the code doesn't work.

....

try
{
throw Exception();
}
catch(exception &e)
{
cout << e.what() << endl;
}
....

here e is a reference to the new Exception() created so
at run-time e.what() should point to my Exception class
and to print "exception!" but it doesn't do that and print
9Exception ... why?
May 16 '07 #6
Hi

Zeppe wrote:
josh wrote:
>yes I've forgotten that...... so it print 9Exception but not
my msg string may be I didn't override the right what() ?

no, you did. the problem, as Eric said, is that if you don't put the
reference a new std::exception is created by copy-constructor. And for
the standard exception the what behaves differently that for your class.
No, he did not. In std::exception it is
virtual const char* what() const throw();

So it should read:

class Exception : public exception
{
public:
Exception(string m="exception!") : msg(m) {}
~Exception() throw() {}
const char* what() const throw () { return msg.c_str(); }

private:
string msg;
};

The const is part of the function signature and thus necessary for
overriding while without the throw() part the program would be ill-formed.

Markus
May 16 '07 #7
Markus Moll wrote:
Hi

Zeppe wrote:
>josh wrote:
>>yes I've forgotten that...... so it print 9Exception but not
my msg string may be I didn't override the right what() ?

no, you did. the problem, as Eric said, is that if you don't put the
reference a new std::exception is created by copy-constructor. And for
the standard exception the what behaves differently that for your class.

No, he did not.
Damn lunch break! I know I should have checked before sending, but I was
hungry... :)

Sorry guys

Regards,

Zeppe
May 16 '07 #8
On 16 Mag, 14:05, Markus Moll <markus.m...@esat.kuleuven.bewrote:
Hi

Zeppe wrote:
josh wrote:
yes I've forgotten that...... so it print 9Exception but not
my msg string may be I didn't override the right what() ?
no, you did. the problem, as Eric said, is that if you don't put the
reference a new std::exception is created by copy-constructor. And for
the standard exception the what behaves differently that for your class.

No, he did not. In std::exception it is
virtual const char* what() const throw();

So it should read:

class Exception : public exception
{
public:
Exception(string m="exception!") : msg(m) {}
~Exception() throw() {}
const char* what() const throw () { return msg.c_str(); }

private:
string msg;

};

The const is part of the function signature and thus necessary for
overriding while without the throw() part the program would be ill-formed.

Markus
yes that was my wrong (and also to make Exception not a reference) now
it works!!!

May 16 '07 #9
On May 16, 1:04 pm, Erik Wikström <eri...@student.chalmers.sewrote:
On 16 Maj, 13:01, josh <xdevel1...@gmail.comwrote:
Hi I have this code:
class Exception : public exception
{
public:
Exception(string m="exception!") : msg(m) {}
~Exception() throw() {}
const char* what() { return msg.c_str(); }
private:
string msg;
};
int main()
{
try
{
throw Exception();
}
catch(exception e)
{
cout << e.what() << endl;
}
return 0;
}
when I run it I don't have print out my message "exception!" but
St9exception
Because you catch the exception by value, so you copy-construct a new
std::exception from the Exception that was thrown, catch the exception
by reference instead and it will work:
catch (exception& e)
Just a detail, but he's probably not going to be modifying the
object, so:
catch ( exception const& e )
would be more appropriate. (In practice, in the case of
exceptions, I don't think it makes much difference, but using
const systematically when appropriate is a good habit to get
into.)

--
James Kanze (Gabi Software) email: ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 16 '07 #10

josh <xd********@gmail.comwrote in message ...
>
I do it but still the code doesn't work.
...

try{
throw Exception();
}
catch(exception &e){
cout << e.what() << endl;
}
...

here e is a reference to the new Exception() created so
at run-time e.what() should point to my Exception class
and to print "exception!" but it doesn't do that and print
9Exception ... why?
Catch the right thing!

catch( Exception const &e ){
cout << e.what() << endl;
}

..... or, re-throw() the std::exception() in your derived class.

I am guessing (have not tested this yet), so, try it, see what happens.

--
Bob R
POVrookie
May 16 '07 #11

BobR <re***********@worldnet.att.netwrote in message ...
>
josh <xd********@gmail.comwrote in message ...
I do it but still the code doesn't work.
...
try{ throw Exception(); }
catch(exception &e){ cout << e.what() << endl; }
...

here e is a reference to the new Exception() created so
at run-time e.what() should point to my Exception class
and to print "exception!" but it doesn't do that and print
9Exception ... why?
Hi Bob.... Oh wait, I'm Bob! <G[answering my own post]

Hi josh,

Ok, after a very little testing, it seems that your class (derived from
std::exception) 'slices', removing your '*.what() when passed to the
'catch(std::exception&)'. By the time I downcasted it to 'Exception' there
is a problem with 'const' which I couldn't find a combination to (for the
few minutes I tried).
[ time for an expert to 'splain it. <G]

>
Catch the right thing!
// catch( Exception const &e ){
catch( Exception &e ){ // 'const' no work.
cout << e.what() << endl;
}
.... or, re-throw() the std::exception() in your derived class.
I am guessing (have not tested this yet), so, try it, see what happens.
If you derive your class from 'std::runtime_error', the 'slicing' does not
happen.
( no '*.what()' in 'Exception3' to slice, duh! )

class Exception3 : public std::runtime_error { public:
Exception3( std::string const &msg = "exception3!")
: std::runtime_error( msg ){}
};

{ // main or function
try{
throw Exception3();
}
catch( std::exception const &e ){
cout<<"caught std::exception= " << e.what() << std::endl;
} // catch( exception& )

try{
throw Exception();
}
catch( std::exception const &e ){
cout<<"caught std::exception= " << e.what() << std::endl;
} // catch( exception& )
}
// output: caught std::exception= exception3!
// output: caught std::exception= 9Exception // sliced

Is there a reason you cannot use 'Exception3'?
( remember, if you just want to catch *any* exception, you can set up
default handlers.)

--
Bob R
POVrookie
May 17 '07 #12

BobR <re***********@worldnet.att.netwrote in message ...
josh <xd********@gmail.comwrote in message ...
I do it but still the code doesn't work.
...
try{ throw Exception(); }
catch(exception &e){ cout << e.what() << endl; }
...
here e is a reference to the new Exception() created so
at run-time e.what() should point to my Exception class
and to print "exception!" but it doesn't do that and print
9Exception ... why?

Catch the right thing!
catch( Exception const &e ){
cout << e.what() << endl;
}
.... or, re-throw() the std::exception() in your derived class.
I am guessing (have not tested this yet), so, try it, see what happens.
[ Answering my own post again! ]
Hey, always try just one more thing!! Duh!

try{
throw Exception();
}
// catch( std::exception const &e ){ // no 'const'
catch( std::exception &e ){
Exception *ex = dynamic_cast<Exception*>( &e );
if( ex ){
cout<<"caught std::exception= "<<ex->what()<<std::endl;
}
} // catch(exception&)

// output: caught std::exception= exception!

--
Bob R
POVrookie
May 17 '07 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Mayer Goldberg | last post by:
Can someone please explain the motivation behind the following restriction in the language: I define an interface and two classes implementing it: public interface InterA {} public class B...
18
by: Ken | last post by:
Hi. Can anyone refer me to any articles about the compatibility between c++ polymorphism and real-time programming? I'm currently on a real-time c++ project, and we're having a discussion...
3
by: Patchwork | last post by:
Hi Everyone, Please take a look at the following (simple and fun) program: //////////////////////////////////////////////////////////////////////////// ///////////// // Monster Munch, example...
4
by: Leslaw Bieniasz | last post by:
Cracow, 20.09.2004 Hello, I need to implement a library containing a hierarchy of classes together with some binary operations on objects. To fix attention, let me assume that it is a...
16
by: ChInKPoInt [No MCSD] | last post by:
I am using Visual Studio 2K3 writing a ASP.NET web application. Is there a way to force the C# compiler to catch possible exception? In Java, all exceptions thrown MUST BE caught, otherwise...
13
by: junw2000 | last post by:
Is C++ Exception handling useful? think it is too complicated. What kinds of project need to use it? Thanks.
11
by: chsalvia | last post by:
I've been programming in C++ for a little over 2 years, and I still find myself wondering when I should use polymorphism. Some people claim that polymorphism is such an integral part of C++,...
1
by: usenet | last post by:
I wrote some sample code (see below) for nested exception throwing i.e. my catch blocks are throwing exceptions of their own (for simplicity I used standard exceptions). I am getting some...
1
weaknessforcats
by: weaknessforcats | last post by:
Introduction Polymorphism is the official term for Object-Oriented Programming (OOP). Polymorphism is implemented in C++ by virtual functions. This article uses a simple example hierarchy which...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.