C++异常处理(try catch)

一、介绍

基本内容:

  • C++ 异常处理机制会涉及 try、catch、throw 三个关键字(注意没有 finally 关键字)
  • 程序的错误大致可以分为三种,分别是语法错误、逻辑错误和运行时错误:C++ 异常(Exception)机制就是为解决运行时错误而引入的。
  • C++ 规定,异常类型可以是 int、char、float、bool 等基本类型,也可以是指针、数组、字符串、结构体、类等聚合类型。
  • C++ 语言本身以及标准库中的函数抛出的异常,都是 exception 类或其子类的异常。(规则和格式)

C++ 异常处理的流程,具体为:抛出(Throw)–> 检测(Try) --> 捕获(Catch)
异常必须显式地抛出,才能被检测和捕获到;如果没有显式的抛出,即使有异常也检测不到。

二、示例

#include <iostream>
#include <exception>
#include <thread>

using namespace std;
//自定义异常类
class CStudentExc
{
public:
    CStudentExc(): m_flag(1){ };
    CStudentExc(int num): m_flag(num){ }

    void what() const
    {
        if(1 == m_flag)
        {
            cout<<"Error: m_flag is 1."<<endl;
        }
        else if(2 == m_flag)
        {
            cout<<"Error: m_flag is 2."<<endl;
        }
        else
        {
            cout<<"Error: m_flag is " << m_flag <<endl;
        }
    }
private:
    int m_flag;//不同的错误类型
};

int test_throw(const int type)
{
    switch(type)
    {
        case 1:
            throw 1;
            break;
        case 2:
            throw 2.2;
            break;
        case 3:
            throw "string 3";
            break;
        case 4:
            throw CStudentExc();
            break;
        case 5:
            throw CStudentExc(2);
            break;
        case 6:
            throw CStudentExc(3);
            break;
    }
    std::cout<< "test_throw end"<< std::endl;
    return 0;
}

int test_try_catch(const int type)
{
    try{
        test_throw(type);
    }
    catch(int &e)
    {
        std::cout<< "int :"<< e << std::endl;
    }
    catch(float &e)
    {
        std::cout<< "float :"<< e << std::endl;
    }
    catch(double &e)
    {
        std::cout<< "double :"<< e << std::endl;
    }
    catch(std::string &e)
    {
        std::cout<< "std::string :"<< e << std::endl;
    }
    catch(const char *e)
    {
        std::cout<< "const char * :"<< e << std::endl;
    }
    catch(const CStudentExc &e)
    {
        e.what();
    }
    catch(std::exception &e)
    {
        std::cout<< "std::exception :"<< e.what() << std::endl;
    }
    return 0;
}

int main(int argc, char **argv)
{
    test_try_catch(1);  //throw int
    test_try_catch(2);  //throw float 实际是double
    test_try_catch(3);  //throw string
    test_try_catch(4);  //
    test_try_catch(5);  //
    test_try_catch(6);  //
    test_try_catch(100);  //exit

    return 0;
}

输出

int :1
double :2.2
const char * :string 3
Error: m_flag is 1.
Error: m_flag is 2.
Error: m_flag is 3
test_throw end
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值