473,569 Members | 2,735 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

what() method of exceptions derived form std::exception

Hi,

I have an exception class for winapi errors (returns a formated error mesage,
usign ::GetLastError( ) et al, with what()).

It looks like this:

class WinapiException : public std::exception
{
public:
WinapiException (const std::string & extraInfo);
virtual const char* what() const throw();
private:
std::string _extraInfo;
};

WinapiException ::WinapiExcepti on(const std::string & extraInfo)
:_extraInfo(ext raInfo)
{
// Nothing
}

The problem is the what() method. Mine looks like this:

const char* WinapiException ::what() const throw()
{
std::string rc;

rc = typeid(this).na me();

// errorString formats the winapi error message and returns an std::string
rc += "GetLastErr or reports:\n" + errorString(::G etLastError());

if( _extraInfo.size () > 0)
{
rc += "\nExtra Info:\n" + _extraInfo;
}
else
{
rc += "\nNo extra info available.";
}

return rc.c_str(); // here's the problem!!!
}

The what() returns a const char* that points to something that has already
been destroyed and freed.

What's the best solution for this? O:-)
Jul 19 '05 #1
4 8074
On Tue, 04 Nov 2003 11:57:22 +0100, Boogie El Aceitoso
<fr****@telefon ica.net> wrote:

return rc.c_str(); // here's the problem!!!
}

The what() returns a const char* that points to something that has already
been destroyed and freed.

What's the best solution for this? O:-)


I am not sure that you have given us enough information to confidently
state a best solution. I can see several ways out.

1. You could make rc a non-static data member of your class.
2. You could declare rc static in the member function.
3. You could declare rc a static data member of the class.
4. You could allocate a dynamic array for the array. But that is
almost always more trouble than its worth. Who deletes the array?

Anyway, there are four ways of handling the problem. I might make it
a data member (static or non-static).
--

Best wishes,

Bob
Jul 19 '05 #2

"Boogie El Aceitoso" <fr****@telefon ica.net> wrote in message news:7f******** *************** *********@4ax.c om...

The what() returns a const char* that points to something that has already
been destroyed and freed.

The easiest way is to keep the data in a string which is a member of the exception
object.

There are two ways you could do this:

1. You could just add another member "what_strin g" and fill it in rather than "rc"
in your what() function (you could even notice if this had been set and avoid recomputing
the string on subsuequent calls to what()).

2. The WinapiException could do what you now do in the what() function and store only the
"whatString " rather than the extrainfo in the object.
Jul 19 '05 #3
Boogie El Aceitoso <fr****@telefon ica.net> wrote in message news:<7f******* *************** **********@4ax. com>...

I have an exception class for winapi errors (returns a formated error mesage,
usign ::GetLastError( ) et al, with what()).

It looks like this:

class WinapiException : public std::exception
{
public:
WinapiException (const std::string & extraInfo);
virtual const char* what() const throw();
private:
std::string _extraInfo;
};

WinapiException ::WinapiExcepti on(const std::string & extraInfo)
:_extraInfo(ext raInfo)
{
// Nothing
}

The problem is the what() method. Mine looks like this:

const char* WinapiException ::what() const throw()
{
std::string rc;

rc = typeid(this).na me();

// errorString formats the winapi error message and returns an std::string
rc += "GetLastErr or reports:\n" + errorString(::G etLastError());

if( _extraInfo.size () > 0)
{
rc += "\nExtra Info:\n" + _extraInfo;
}
else
{
rc += "\nNo extra info available.";
}

return rc.c_str(); // here's the problem!!!
}

The what() returns a const char* that points to something that has already
been destroyed and freed.


The answer is simple: have what() return something that isn't already
destroyed and freed.

WinapiException ::WinapiExcepti on(const std::string & extraInfo)
:_extraInfo(typ eid(this).name( ))
{
// errorString formats the winapi error message and returns an
std::string
_extraInfo += "GetLastErr or reports:\n" +
errorString(::G etLastError());

if (extraInfo.size () > 0)
{
_extraInfo += "\nExtra Info:\n" + extraInfo;
}
else
{
_extraInfo += "\nNo extra info available.";
}
}

const char* WinapiException ::what() const throw()
{
return _extraInfo.c_st r();
}

This has the added advantage that ::GetLastError( ) will be called at
the point when the exception is thrown, rather than later when the
exception is reported and its value may have been affected by
intervening system calls.

--
Stephen M. Webb
Jul 19 '05 #4
Boogie El Aceitoso wrote:
...
I have an exception class for winapi errors (returns a formated error mesage,
usign ::GetLastError( ) et al, with what()).

It looks like this:

class WinapiException : public std::exception
{
public:
WinapiException (const std::string & extraInfo);
virtual const char* what() const throw();
private:
std::string _extraInfo;
};

WinapiException ::WinapiExcepti on(const std::string & extraInfo)
:_extraInfo(ext raInfo)
{
// Nothing
}
...


Just to add something less relevant to other people's replies:

The above definition of 'WinapiExceptio n' class is ill-formed. Your
class 'WinapiExceptio n' contains a subobject of type 'std::string'. The
'std::string's destructor has no exception specification (allows all
types of exceptions), which immediately means that the implicitly
declared destructor of class 'WinapiExceptio n' will also allow all types
of exceptions (see 15.4/13). At the same time the virtual destructor of
'std::exception ' is declared with 'throw()' exception specification (no
exceptions allowed). According to 15.4/3, the above definition of
'WinapiExceptio n' is ill-formed, since the declaration of virtual
function 'WinapiExceptio n::~WinapiExcep tion' is less restrictive than
the exception specification of base class' virtual function it overrides
('std::exceptio n::~exception') . (See also an example in 15.4/13, which
is similar to yours in this respect.)

It is very likely that your compiler accepts the above code. But don't
be surprised if one day it will start complaining.

--
Best regards,
Andrey Tarasevich

Jul 19 '05 #5

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

Similar topics

3
7283
by: Paul Miller | last post by:
Is there any particular good reason to inherit from exceptions.Exception? I've never seen any code that depends on what the base class(es) of a raised exception is (are). My use case is in a game I am writing. The code for my Game class contains the following: class Game (object): def start (self):
2
1438
by: Maurice LING | last post by:
Hi, I'm trapping exceptions with these codes... try: except IOError: except TypeError: except:
3
11007
by: Noah Roberts | last post by:
I am having some problems with deriving the std::exception class. My compiler (g++-2.95) works with it just fine, but it does in a lot of broken cases. I have a user/developer that can't compile the following code: class CFENException : public std::exception { std::string _what; public:
3
3484
by: Pierre Rouleau | last post by:
The std::exception class defined in the Standard C++ <exception> header specifies that the constructors could throw any exception becuase they do not have a throw() specification. Why is that? Is this because there could be an exception thrown when the code creates a std::exception? I would assume that is not the case. However, if I want...
1
1517
by: vlar | last post by:
01/30/2004 I have posted "Serious bug in ngen.exe" in this thread but so far (in .NET 1.1 SP1) this bug is not yet fixed !!! So I am repeating this post again: Ngen stops catching of derived exception in multi dll application ! I have reproduced this bug in the very simple application which consists of 2 dll and 1 exe file. Its behaviour...
5
6075
by: mthgk | last post by:
I have a C# MDI app. The child forms do alot of work, so this work is perfomed on a different thread created using ThreadPool.QueueUserWorkItem(). Because the status of the work is important to the user, I post the results in a richTextBox on the child form. I have created an event to do this since it is best to update the controls using the...
4
6386
by: Divick | last post by:
Hi all, I want to subclass std::exception so as to designate the type of error that I want to throw, out of my classes, and for that I need to store the messages inside the exception classes. I want to use std::string to do that so that I don't have to deal with all the hustle of dealing with char *'s but as listed in the page (see link)...
2
1490
by: Lance.Jellyfish | last post by:
Hi, right now, something is very strange... The .net exception handler is disabled!! When I throw an exception or if I try to use an object that is not set ( = null) I do not receive any exceptions at all. I tried to use the Application.ThreadException event but nothing happens, the execution just stops and the next message in the message...
6
1480
by: PGP | last post by:
Where will i look to find potential exceptions thrown by a method? I am looking at Object Browser and couldnt find any, MSDN doesnt seem to provide a consistent format for this either. Any advice would be appreciated.
0
7694
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8118
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7964
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6278
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.