473,386 Members | 1,720 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,386 software developers and data experts.

Extend std::exception

6
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 4988
Banfa
9,065 Expert Mod 8TB
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 Expert 512MB
@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 Expert Mod 8TB
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 Expert 512MB
@weaknessforcats,

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
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 Expert Mod 8TB
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
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 Expert 512MB
@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 Expert Mod 8TB
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_range (which also inherits std::exception), the compiler can not convert std::out_of_range to Exception (from your code) because std::out_of_range 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
dinopc
6
Thank you.
Sep 9 '10 #11

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

Similar topics

3
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...
4
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...
3
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? ...
2
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...
3
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...
4
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...
2
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: ...
3
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...
5
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...
3
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....
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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
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...

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.