473,656 Members | 2,983 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with Extending std::exception class

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) below, it
is not advisable to use std::string in my exception classes.

The rational given is not very clear to me but is there no other way
out but to use char * for storing the messages ? Can somebody help me
provide some guideline to subclass the std::exception in a clean and
safe way?

http://www.boost.org/more/error_handling.html

Thanks,
Divick

Jan 11 '06 #1
4 6396
Divick wrote:
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.
Or you could use several different exception classes, one for each type
of error:

throw NegativeNumberE xception();
throw ZeroException() ;
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) below, it
is not advisable to use std::string in my exception classes.
Right. You could always do something like:

throw MyException( "Negative number" );

No std::string, no hassle.
The rational given is not very clear to me but is there no other way
out but to use char * for storing the messages ? Can somebody help me
provide some guideline to subclass the std::exception in a clean and
safe way?

http://www.boost.org/more/error_handling.html


The link you cite does an excellent job. Dave Abrahams is one of the
preeminent gurus when it comes to exception safety. You should listen
to him.

The rationale for not using std::string is that its copy constructor
could throw an exception. So, if you are the process of throwing your
own exception, and your exception class (or a member thereof) throws an
exception when its copy constructor is invoked, terminate() is
immediately called, which is, generally speaking, bad news. Likewise,
Abrahams notes that a constructor that throws can be bad news, but it
won't necessarily invoke terminate.

Cheers! --M

Jan 11 '06 #2
>>Or you could use several different exception classes, one for each type
of error: throw NegativeNumberE xception();
throw ZeroException() ;
That is what I am doing right now.
Right. You could always do something like:

throw MyException( "Negative number" );

In this case the constructor for MyException is called with the const
char * arguments, and in the constructor of MyException don't I need to
store the char * in a member char *?

Also I want to send some formatted message as well as some extra
information to the user when an exception occurs, for which I have to
pass two string values in the exception like this
MyException("er rro code","error detail");

In this case what shall I do?

Jan 11 '06 #3
Divick wrote:
[snip]
Right. You could always do something like:

throw MyException( "Negative number" );

In this case the constructor for MyException is called with the const
char * arguments, and in the constructor of MyException don't I need to
store the char * in a member char *?

Also I want to send some formatted message as well as some extra
information to the user when an exception occurs, for which I have to
pass two string values in the exception like this
MyException("er rro code","error detail");

In this case what shall I do?


Well, the usual way is, to derive from std::exception and override the
virtual function std::exception: :what(). Alternately, you can derive
from one of its standard child classes, e.g., std::logic_erro r or
std::range_erro r, to which you pass (through the base class
constructor) a single string that will be returned by its what()
function.

If you are extending those classes, you can add whatever members you
want (though you should bear in mind their exception safety, as in the
Abrahams link above), and you can override what() (or provide a
different member function) to return a message composed from the base
class' what() and from your additional members. However, it may be just
as easy and perhaps safer (depending on how you do it) to compose the
message before before throwing the exception, and then just pass the
message to the exception class constructor.

Cheers! --M

Jan 11 '06 #4
Ok that sounds good. Thanks for your help.

Divick

Jan 12 '06 #5

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

Similar topics

3
11022
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:
4
8078
by: Boogie El Aceitoso | last post by:
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:
2
2227
by: Stefan Pantos | last post by:
Dear all, Could someone explain to me the proper use of throw()? As it is used for std::exception. I cannot find anything which describes how it should be used and all the information about exceptions in c++ seem to ignore it completly. I know that it's similar to throws in java but I have no idea of how it should be used. When I say throw() I mean in the way it is used here: class exception {
3
3489
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 to create a new exception class, derived from std::exception (say MyException) then how can I...
3
2316
by: __PPS__ | last post by:
Hi, I've read in documentation to different libraries that their exception classes aren't subclasses from std::exception, and a separate catch statement is required for their exceptions. Always, I don't understand why they do so and want to fix this feature (most of the time, I go to edit source), even in their docs they write like this: try { // Close the database db.close(0); // DbException is not subclassed from std::exception, so //...
11
2268
by: Mike - EMAIL IGNORED | last post by:
On FC4 with g++ using STL and Posix threads and sockets I am catching an exception that is not a std::exception. Any idea what it might be? An outline of my catch macro is below. Thanks, Mike. #define MY_MACRO \
2
6981
by: Darko Miletic | last post by:
Recently I wrote a dll in c++ and to simplify the distribution I decided to link with multithreaded static library (/MT or /MTd option). In debug everything works fine but in release I get this: parseMetadata.obj : error LNK2001: unresolved external symbol "public: __thiscall std::exception::exception(void)" (??0exception@std@@QAE@XZ) 2>libcpmt.lib(string.obj) : error LNK2001: unresolved external symbol "public: __thiscall...
5
6518
by: Miles | last post by:
Hello all, When I subclass std::exception and throw an instance of the subclass, when I call the what() method of the caught exception, it does not call the overridden method. I'm under the impression that std::exception declares what() as a virtual method, so I'm at a loss as to why the subclass's what() is not being called. For example, for this program: #include <exception>
3
6426
by: vainstah | last post by:
Hello Guys and Galls, To start off, I have reached the solution I was looking for, but I would like comments and feedback on the solution I have reached and tips/tricks on making it more elegant. I am not satisfied with the underlying machinery of the solution though. I am an advanced C programmer and most do object-based programming in C++. Please do not reply to this article with references to basic material or obvious tips. An...
0
8296
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8710
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8598
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7310
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4150
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4299
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2721
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.