Skip to Main Content

DevOps, CI/CD and Automation

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Excetion handling and exception class

803336Nov 17 2010 — edited Nov 18 2010
I was looking up exception handling and i came across the following code which was highly recommended. I was hoping you experts out there could
clear a couple of queries that i had...

#include <exception>
using namespace std;

class myexception: public exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
} myex;

int main ()
{
try
{ throw myex; }

catch (exception& e)
{
cout << e.what() << endl;
}
return 0;
}

Now i understood the basics of the above code however i had a couple of questions
1- The above code uses
virtual const char* what() const throw()
here virtual represents a virtual function , const char* represents the return type , what() is the name , now
what does const throw() mean ??, this is the first tme i have come across a function which has perimeters after the name of the function()??
here we have const throw() what does that mean??

2-I understand that we are creating our own exception class derived from the base exception class to throw out errors. So if i need to define like 12 custom errors in my program will i need to create 12 different error classes or is there a better way ??

3-I checked the what function out in exception and it is virtual. From my understanding of virtual functions I understand that if a base class
has a virtual function then that function could be overridden in a derived class or in other words the virtual function in the base class can be replaced by
the function of the derived class even if an instance of the base class is created .

However for this to happen we have to use pointers as such
BaseClass *a = new DerivedClass; a->somefunction() ;
//Now some function present in DerivedClass will be called as somefunction
//was marked virtual in the base class.

Now my question is as follows:
since we are using "exception& e" this means we expect our what function from the myexception class we just created
to be called here rite ?? I agree but where in our code is exception *instance = new myexception stated or expressed
is it present in the throw??

Your suggestions and help would be highly appreciated thanks....
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 16 2010
Added on Nov 17 2010
6 comments
512 views