exception

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.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值