Standard exception class in STL has following structure
class exception {
public:
exception();
exception(const char * const &message);
exception(const char * const &message, int);
exception(const exception &right);
exception& operator=(const exception &right);
virtual ~exception();
virtual const char *what() const;
};
Simple example for defining users' own exception. The key point is to implement pure virtual function what().
#include <iostream>
#include <exception>
using namespace std;
class myexception : public exception {
public:
virtual const char* what() const throw(){
return "my exception.";
}
};
int main(){
int* myarray;
try{
myarray = new int(1000);
}catch(exception& e){
cout << "Exception: " << e.what() << endl;
}
delete myarray;
myarray = nullptr;
return 0;
}
exception is base class for all exceptions in stl.
1. std::bad_alloc, can be thrown by new.
2. std::bad_cast, can be thrown by dynamic_cast.
3. std::bad_exception, useful device to handle unexpected exceptions in a C++ program.
4. std::bad_typeid, can be thrown by typeid.
5. std::logic_error, an exception that theoretically can be detected by reading the code.
5. std::domain_error, this is an exception thrown when a mathematically invalid domain is used.
6. std::invalid_argument , can be thrown due to invalid arguments.
7. std::length_error, can be thrown when a too big std::string is created.
8. std::out_of_range, can be thrown by the at method from for example a std::vector and std::bitset<>::operator[]().
9. std::runtime_error, an exception that theoretically can not be detected by reading the code.
9. std::overflow_error, can be throw if a mathematical overflow occurs.
10. std::range_error, can occured when you try to store a value which is out of range.
11. std::underflow_error, can be thrown if a mathematical underflow occurs.