BZ易风

导航

 

编写自己的异常类

  • 自己的异常类 需要继承于  exception
  • 重写  虚析构   what()
  • 内部维护以错误信息 字符串
  • 构造时候传入 错误信息字符串,what返回这个字符串
  • string 转 char *   .c_str();
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include <string>

class myOutofRangeException :public exception
{
public:
    myOutofRangeException(string msg)
    {
        this->m_ErrMsg = msg;
    }
    ~myOutofRangeException()
    {
        
    }

    char const* what() const
    {
        return this->m_ErrMsg.c_str();  // .c_str() 字符串转char*
    }

    string m_ErrMsg;
};

class Person
{
public:
    Person(string name, int age)
    {
        this->m_Name = name;
        if (age < 0 || age>200)
        {
            throw myOutofRangeException("年龄越界了!");
        }
        else
        {
            this->m_Age = age;
        }
    }

    string m_Name;
    int m_Age;
};
void test01()
{
    try
    {
        Person p1("张三", 300);
    }
    catch (exception& e)    //使用系统提供的标准异常 多态
    {
        cout << e.what() << endl;
    }
}

int main()
{
    test01();
    system("Pause");
    return 0;
}

结果:

 

posted on 2021-08-25 14:06  BZ易风  阅读(71)  评论(0编辑  收藏  举报