zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    shell脚本的常用参数
    Qt中使用Protobuf简单案例(Windows + msvc)
    使用PicGo和Typora写Markdown
    CentOS7安装protobuf(C++)和简单使用
    protobuf编译、安装和简单使用C++ (Windows+VS平台)
    protocol buffers 文档(一)-语法指导
    Base64编码和其在图片的传输的应用
    Qt程序打包发布
    Qt中的Label和PushButton背景图自动缩放设置
    TCP的粘包和拆包问题及解决
  • 原文地址:https://www.cnblogs.com/DLzhang/p/3978372.html
Copyright © 2011-2022 走看看