首页 > 其他 > 详细

try-catch 异常捕获学习

时间:2019-08-04 11:51:13      阅读:122      评论:0      收藏:0      [点我收藏+]
#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;
}

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

try-catch 异常捕获学习

原文:https://www.cnblogs.com/zhangkele/p/11297097.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!