try-catch 异常捕获学习

#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
using namespace std;

//对于不同的异常可以采取不同的catch块进行捕捉
//对于一部分可以统一处理
int main(int argc, const char *argv[])
{
    try
    {
        int i;
        cin >> i;
        if(i == 0)
            throw runtime_error("出现运行期错误");
        else if(i == 1)
            throw invalid_argument("非法参数");
        else if(i == 2)
            throw logic_error("逻辑错误");
        else
            throw out_of_range("越界错误");
    }
    catch(...) //能捕获所有的异常
    {
           cout << "xxxxxxxxxxxxxxxxxxx" << endl;
    }
/*     catch(exception &e)
    {
        cout << "异常信息:" << e.what() << endl;
    }
    catch(runtime_error &e)
    {
        cout << "runtime_error :" << e.what() << endl;
    }
    catch(invalid_argument &e)
    {
        cout << "invalid_argument:" << e.what() << endl;
    } */
    cout << "继续运行" << endl;
    return 0;
}

  将代码分别注释 分别进行编译运行你就理解了

猜你喜欢

转载自www.cnblogs.com/zhangkele/p/11297097.html
今日推荐