473,847 Members | 2,464 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does std::exception constructor specifies it can throw any ?


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 guarantee that creating
an instance of MyException will not generate any exception?

class MyException : public std::exception
{
public:
explicit MyException(int someinfo) throw();
// violates specs of std::exception
.....
};

Thanks for any information on this topic.

Pierre R.
Jul 23 '05 #1
3 3511
"Pierre Rouleau" <Pi************ @impathnetworks .com> wrote in message
news:J6nVd.2948 2
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.
All of the 5 functions of class std::exception are declared with throw(),
according to the standard. The constructor, copy constructor, operator=,
and destructor do nothing (though the standard does not require that they do
nothing), so of course they don't throw. The pure virtual what function
must be defined in the derived classes as not throwing exceptions either (so
it will have to return a string stored inside the exception object).

But the constructor of the derived class may throw. If your exception
stores the names and values of the environment variables, this means
(usually) allocating dynamic memory to store all the info, and thus the
constructor may throw if it runs out of memory.

The throw() specification on a function does not just mean that the function
does not throw, but rather that the function throws nothing or calls
std::terminate. The call to std::terminate happens if the function throws
an exception either directly or calls a function (virtual or not) that
throws an exception.

If you declare your derived class as

class DerivedExceptio n : public std::exception {
public:
DerivedExceptio n() throw() { }
};

does it fail compile? It passes compile on my computer, Borland C++ 6.

However, if I want to create a new exception class, derived from
std::exception (say MyException) then how can I guarantee that creating
an instance of MyException will not generate any exception?
You can use try-catch.

DerivedExceptio n::DerivedExcep tion() {
try { stuff that may throw; }
catch (...) { }
}

But be aware that the compiler generated initialization list calls the
default constructor of the base class, plus the default constructor of
contained objects. If any of these throw, then you program will call
std::terminate. So be sure that the base class constructor does not throw,
which is the case for std::exception, and that the constructors of your
contained objects don't throw.

To garauntee this, you could allocate objects on the heap, for example:

class MyException : public std::exception {
public:
MyException() throw();
const char * what() const throw() { return d_what; }
private:
struct Details;
Details * d_details;
const char *const d_what;
};

struct MyException::De tails {
std::string name;
std::string value;
}

MyException::My Exception() : std::exception( ), d_details(), d_what() {
try {
d_details = new Details;
d_details->name = "hello";
d_details->value = "world";
}
catch (...) { delete d_details; d_what = NULL; }
}
class MyException : public std::exception
{
public:
explicit MyException(int someinfo) throw();
// violates specs of std::exception
....
};

Thanks for any information on this topic.


Jul 23 '05 #2
Siemel Naran wrote:
"Pierre Rouleau" <Pi************ @impathnetworks .com> wrote in message
news:J6nVd.2948 2

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.

All of the 5 functions of class std::exception are declared with throw(),
according to the standard.


Thanks for the good explanation on the topic. I should have mentionned
that I was using an old (and non compliant) compiler (VC6) where the
exception class member functions are defined without the throw()
specification.

We also have Visual Studio .Net 2003 (VC7) and the <exception> file that
comes with that version of the compiler does not have the throw()
specification either.

I was under the impression that VC7 was C++ standard compliant. It
appears not. Are there newer version of the header files available for
Microsoft VC7?

Thanks again.

Pierre Rouleau
Jul 23 '05 #3
"Pierre Rouleau" <Pi************ @impathnetworks .com> wrote in message
news:LvZVd.5349 4
Siemel Naran wrote:

All of the 5 functions of class std::exception are declared with throw(), according to the standard.


Thanks for the good explanation on the topic. I should have mentionned
that I was using an old (and non compliant) compiler (VC6) where the
exception class member functions are defined without the throw()
specification.

We also have Visual Studio .Net 2003 (VC7) and the <exception> file that
comes with that version of the compiler does not have the throw()
specification either.

I was under the impression that VC7 was C++ standard compliant. It
appears not. Are there newer version of the header files available for
Microsoft VC7?


Don't know about MSVC 7 and exceptions, and the best place to ask in the
microsoft newsgroups (there's one in usenet, and may in msdn.microsoft. com).

Anyway, if the base class constructor declares with the throw spec, the
derived class constructor can declare without the throw spec. And vice
versa: if the base class constructor declares without the throw spec, the
derived class constructor can declare with the throw spec. So whether or
not the MSVC <exception> headers are compliant, I think should not matter.
Jul 23 '05 #4

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

Similar topics

3
11042
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
8085
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
2235
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
2326
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 //...
3
2160
by: bobueland | last post by:
Sometimes the best way to understand something is to understand the mechanism behind it. Maybe that is true for exceptions. This is a model I have right now (which probably is wrong) 1. When a runtime error occurs, some function (probably some class method) in Python is called behind the scenes. 2. That function goes into a global table having error types in one column and corresponding flags in another (and probably other columns used...
4
6412
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) below, it is not advisable to use std::string in my exception classes. The rational given is not...
11
2294
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 \
3
7734
by: Sendil kumar | last post by:
Hi All, Problem Stetement:I have a problem in getting stack trace when I ues std::exception. In my code, I allocate virtual memory for certain kind of processing and will throw the std::bad_alloc exception if memory could not be allocated. I have never handled the bad_alloc, so, what I expect here is a stack trace from windows showing the excact location where the exception was thrown. But, to my surprise it gives only the windows ...
3
6439
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
9879
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9727
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
10981
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
10643
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
10330
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...
1
7879
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
7050
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5907
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3158
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.