473,785 Members | 2,480 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Extend std::exception

6 New Member
Hello, i am italian, I apologize for my English.

I would like to extend the class std::exception:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <ctype.h>
  5. #include <sys/types.h>
  6. #include <errno.h>
  7. #include <dirent.h>
  8. #include <stdarg.h>
  9. #include <list>
  10. #include <string>
  11. #include <vector>
  12. #include <exception>
  13.  
  14. using namespace std;
  15.  
  16. class Exception : public std::exception
  17. {
  18. public:
  19.   Exception(const std::exception& e);
  20.  
  21.     Exception(const Exception& e);
  22.  
  23.     Exception(const std::string& s);
  24.  
  25.     Exception& operator= (const Exception& rhs);
  26.     void swap(Exception& x);
  27.  
  28.     virtual ~Exception() throw();
  29.  
  30. public:
  31.  
  32.     virtual const string getMessage() const;
  33.  
  34.     /**
  35.      * Returns getMessage()
  36.      */
  37.     virtual const char* what() const throw();
  38.  
  39. private:
  40.     string            m_msg;
  41. };
  42.  
  43. Exception::Exception(const std::string& s)
  44. {
  45.   m_msg = s;
  46.  
  47. Exception::Exception(const std::exception& e)
  48.   : std::exception(e)
  49. {
  50.  
  51. Exception::~Exception() throw()
  52. {
  53. }
  54.  
  55. Exception& Exception::operator=(const Exception& rhs)
  56. {
  57.     Exception(rhs).swap(*this);
  58.     return *this;
  59. }
  60.  
  61. void Exception::swap(Exception& rhs)
  62. {
  63.   std::swap(static_cast<std::exception&>(*this), static_cast<std::exception&>(rhs));
  64.   std::swap(m_msg, rhs.m_msg);
  65. }
  66.  
  67. const string Exception::getMessage() const
  68. {
  69.   return m_msg;
  70. }
  71.  
  72. const char* Exception::what() const throw()
  73. {
  74.   return getMessage().c_str();
  75. }
  76.  
  77. int main()
  78. {
  79.   string s("22");
  80.  
  81.   try
  82.   {
  83.     s.erase(10,10);
  84.   }
  85.   catch (Exception &tExc)
  86.   {
  87.     cout << tExc.getMessage() << endl;
  88.   }
  89.  
  90.   return 0;
  91. }
  92.  
  93.  
When I run this piece of code the program goes into 'core', Can you help me understand what's the problem?

Thank you
Sep 8 '10 #1
10 5041
Banfa
9,065 Recognized Expert Moderator Expert
If std::string is throwing an exception you are not catching it. std::string will be throwing either std::exception or more likely an exception derived from std::exception from the stdexcept header.

You catch your own exception, this will not be a match for the exception thrown by std::string, it can not be, std::string is compiled without access to your Exception class and so can not through that class. So the exception handler will not be entered because you have to catch the thing thrown or a super-class of the thing thrown. The unhandled exception then causes you program to core dump.


You derive from std::exception so that you have an exception that you can throw from your own code but that people using your code can catch easily using std::exception as well as all any other exceptions.
Sep 8 '10 #2
Oralloy
988 Recognized Expert Contributor
@dinopc,

May I ask why you're implementing assignment in terms of std::swap, which recurses back to your assignment? This recursion may well cause an infinite stack extension, ultimately resulting in a core dump.

Which is to say, I really don't understand your modified assignment operator - what are you trying to achieve?

Of course, my analysis of your code may be wrong, in which case, ignore me.

Cheers!
Sep 8 '10 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
Also, when you derive from std::exception, you catch an std::exception reference and not an object of your own derived class.

virtual functions are used to get the correct what() call.
Sep 8 '10 #4
Oralloy
988 Recognized Expert Contributor
@weaknessforcat s,

I respect your observation and judgement. What do you think he's trying to do with the assignment operator and std::swap invocations? That's what's got me confused.

Thanks,
Oralloy
Sep 8 '10 #5
dinopc
6 New Member
I'm sorry but unfortunately I did not understand any of your comments.

The process goes Signal = [6].

Can you help me understand how can I fix this?
Sep 9 '10 #6
Banfa
9,065 Recognized Expert Moderator Expert
change your catch statement to

Expand|Select|Wrap|Line Numbers
  1.   catch (std::exception &e)
  2.   {
  3.     cout << e.what() << endl;
  4.   }
Sep 9 '10 #7
dinopc
6 New Member
I wanted to avoid putting a 'catch (std:: exception & exc)' since I created a class that inherits from 'std:: exception', hoping to catch exceptions even standard, otherwise it makes no sense it inherit from 'std:: exception'.

Thank you.
Sep 9 '10 #8
Oralloy
988 Recognized Expert Contributor
@dinopc,

You do understand that your Exception is an instance of (is-a) std::exception, but that std::exception is not an instance of Exception?

It sounds like you're confusing the meaning of the "is-a" relationship.

Banfa's suggestion is that you catch all thrown std::exception instances at the top level - so you can actually look at the cause of your error. This trap will also catch all instances of Exception.

If you were to catch Exception, as in my example here, then your code will not catch std::exception; even though you've built a constructor which takes std::exception as the argument. This is because the exception stack looks at type, but does not implicitly coerce types in the way compiled code does. If it did, there'd be a massive processing cost, as the C++ run-time would have to inspect every exception at each step to determine if there was a conversion (object constructor, etc) which matched.
Expand|Select|Wrap|Line Numbers
  1. catch (Exception &ex)
  2. {
  3.   // does not catch std::exception
  4.   cout << "Caught Exception: << flush;
  5.   cout << ex.what() << endl << flush;
  6. }
Hopefully that helps.

Luck!
Sep 9 '10 #9
Banfa
9,065 Recognized Expert Moderator Expert
No it makes sense to inherit from std::exception when you want to throw your own exceptions since it lets people catch them in a standard way (through std::exception) .

When you catch an exception you have to catch what is thrown. That means that what is thrown has to be capable of being converted to what is being caught.

The compiler is capable of may different conversions but the one that applies here is its ability to convert a reference to a derived class to a reference to a base class.

That allows the following model to work

Expand|Select|Wrap|Line Numbers
  1. class MyException : public std::exception
  2. {
  3. ... class definition ...
  4. }
  5.  
  6. int main()
  7. {
  8.     try
  9.     {
  10.         throw MyException();
  11.     }
  12.     catch(std::exception &e)
  13.     {
  14.         cout << "caught my exception" << endl;
  15.     }
  16. }
  17.  
The compiler can catch the exception as std::exception because the compiler can convert MyException to std::exception because MyException inherits std::exception.

string::erase throws std::out_of_ran ge (which also inherits std::exception) , the compiler can not convert std::out_of_ran ge to Exception (from your code) because std::out_of_ran ge does not inherit Exception.


Your attempt to inherit from std::exception in order to catch exceptions thrown by the standard library (and others) is doomed to failure because of of type conversion works.

I suggest you just catch in the standard way I gave in post #7. Alternatively you could explain your motives for wanting to catch using this inherited class, what was it you hoped to gain?
Sep 9 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

3
11038
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
8083
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:
3
3504
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...
2
4559
by: ma740988 | last post by:
The hierachy for standard exception lists: bad_alloc, bad_cast, bad_typeid, logic_error, ios_base::failure, runtime_error and bad_exception runtime_error and logic_error has subsets. The question: If I threw all seven exceptions highlighted above. std::exception is the only exception needed within the catch clause? In other words I wouldn't need a 'catch all'? So now: void my_test()
3
2321
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 //...
4
6411
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...
2
6993
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...
3
7729
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 ...
5
6537
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
6436
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
9645
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...
1
10091
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9950
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
8972
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
7499
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
6740
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
5381
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...
2
3646
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
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.