C++ offers an exception class hierarchy that covers a broad range of generic exceptions:
Code:
exception
logic_error
length_error
domain_error
out_of_range
invalid_argument
runtime_error
range_error
overflow_error
underflow_error
bad_alloc
bad_exception
bad_cast
bad_typeid
ios_base::failure
All of those classes are derived from exception, which looks something like this:
Code:
class exception
{
public:
exception() throw();
exception ( const exception& ) throw();
exception& operator= ( const exception& ) throw();
virtual ~exception() throw();
virtual const char *what() const throw();
private:
// ...
};
>throw std::invalid_argument ( "Value must be an integer" );
invalid_argument is defined like so:
Code:
namespace std {
class invalid_argument : public logic_error {
public:
explicit invalid_argument(const string& what_arg);
};
}
The throw statement calls the constructor for class invalid_argument with a string that can be printed in the handler describing the exact problem. Most of the classes described above can be thrown the same way, they are all very similar.
>catch ( std::invalid_argument& ia ) {std::cerr<< ia.what();}
The catch statement knows that an invalid_argument was caught, but it doesn't know where or what happened. The string passed to the constructor when invalid_argument was thrown describes exactly what went wrong according to the programmer, and the what() member function derived from class exception prints that string as a diagnostic message telling the reader exactly what the programmer thought happened.
-Prelude