C++学习之路: 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("出现运行期错误");   //发送一个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;
}

 

posted @ 2014-09-18 00:08  tilly_chang  阅读(1690)  评论(0编辑  收藏  举报