码迷,mamicode.com
首页 > 编程语言 > 详细

C++学习之路: try&catch 语句块处理异常

时间:2014-09-18 00:47:13      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   div   sp   代码   

#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("出现运行期错误");   //发送一个runtime_error异常
        else if(i == 1)
            throw invalid_argument("非法参数");
    }
    catch(runtime_error &e)  
    {
        cout << "runtime_error :" << e.what() << endl;  //e.what()中保存着错误信息
    }
    catch(invalid_argument &e)
    {
        cout << "invalid_argument:" << e.what() << endl;
    }

    cout << "继续运行" << endl;
    return 0;
}

 

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

//异常捕获不到,照样因为core dump
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("非法参数");
    }
    catch(runtime_error &e)
    {
        cout << "runtime_error :" << e.what() << endl;
    }

    cout << "继续运行" << endl;
    return 0;
}

如果没有捕捉到异常则跳过CATCH继续执行后面的代码

 

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(...) //能捕获所有的异常
    {
    
    }
    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;
}

 

C++学习之路: try&catch 语句块处理异常

标签:style   blog   color   io   os   ar   div   sp   代码   

原文地址:http://www.cnblogs.com/DLzhang/p/3978372.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!