【day0402】C++标准异常

来源:互联网 发布:gta5n卡掉帧如何优化 编辑:程序博客网 时间:2024/06/05 05:26

C++定义了很多的标准异常,常见的如下:

    //exception
    //runtime_error
    //range_error 
    //overflow_error
    //underflow_error
    //domain_error
    //invalid_argument 参数异常
    //length_error
    //out_of_range   范围异常
    //bad_alloc    内存分配异常


Demo1:内存分配异常

#include <iostream>using namespace std;class Ram{public:    Ram(){        p = new int[1000000];    }private:    int *p;};int main(){    Ram *ram;    try{        for (int i = 0; i < 10000; ++i){            ram = new Ram();            cout << i << "new successfully!\n";        }    }catch(bad_alloc err){        cout << "new failed!\n";    }    return 0;}

输出:



Demo2:参数异常

#include <iostream>#include <string>#include <bitset>#include <stdexcept> //标准异常//<exception>定义了与异常处理相关的类,声明和函数。//<stdexcept>定义了一些标准的异常类。分为两大类:逻辑错误和运行时错误。其中运行时错误是程序员不能控制的。//    逻辑错误都继承自logic_errorusing namespace std;/*参数异常*/int main(){    int i = 0;    try{        i = 1;        string str1("1010110101");        bitset<10> b1(str1);        cout << "bitset b1 is OK!\n";        i = 2;        //中间插入非数字字符        string str2("1101X10101");        bitset<10> b2(str2);        cout << "bitset b2 is OK!\n";    }catch(invalid_argument err){        cout << "bitset error: b" << i << err.what() << endl;    }    return 0;}

输出:



Demo3:范围异常

#include <iostream>#include <stdexcept>using namespace std;/*范围异常*/class Stu{public:    Stu(int age){        if (0 > age || 140 < age){            throw out_of_range("年龄超出范围(0~140)");        }        this->age = age;    }private:    int age;};int main(){    int i = 0;    try{        i = 1;        Stu tom(22);        cout << "22岁的学生" << endl;        i = 2;        Stu mike(155);        cout << "155岁的学生" << endl;    }catch(out_of_range err){        cout << "年龄错误:学生" << i <<": " << err.what() << endl;    }    return 0;}

输出:



*此外,还可以自定义异常类型。使用模板类定义。





1 0