Hi:
My questions are about std::exception.
I'm trying to define my own custom exception classes, say:
1 2 3 4 5 6 7
|
class IndexOutOfBoundary : public exception
{
};
class InvalidValue : public exception
{
};
|
My understanding is: depending on the types of exception caught, my program is going to take different actions, say:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
try
{
function1();//function1() has a throw statement; might throw either of the two custom exceptions: IndexOutOfBoundary or InvalidValue
}
catch(IndexOutOfBoundary & e)
{
cout << "Index is out of boundary\n"; // toy example
}
catch(InvalidValue & e)
{
cout << "Value is invalid\n"; // toy example
}
catch()
{
cout << "Something else is caught\n";
};
|
Apparently, I'm trying to navigate my program's exception handling process by the custom exception type. Therefore, I don't need to override member functions of std::exception, whose declarations can be found in the link ---
http://www.cplusplus.com/reference/std/exception/exception/
Question 1:
Is it a good style to use exception? If not, please provide an advisable way of using it.
Question 2:
I don't understand the declaration of the member functions in std::exception.
For instance:
1 2 3 4 5 6 7 8
|
class exception {
public:
exception () throw(); // Is it legal? What does it mean by "exception ()"? If throw() is the function name, then "exception ()" should be replaced by an object type thrown. In this case, I think it's "exception".
exception (const exception&) throw(); // similar to the previous question. In addition, what's the extra "const exception &"?
exception& operator= (const exception&) throw();
virtual ~exception() throw();
virtual const char* what() const throw(); // what is "what()"
}
|
I've detailed my questions in the comment. In short, I just have no idea what it is talking about. The link claims
exception () throw ()
is the default constructor. But I've never seen any constructor in this form. What's the postfix
throw ()
? And where is the declaration for "throw()"?
Please enlighten me. Many thanks in advance!