C++ 79 之 自己写异常类

cpp 复制代码
#include <iostream>
#include <string>
using namespace std;

class MyOutOfRange : public exception{ // 选中exception右键 转到定义 复制一份 virtual const char* what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_NOTHROW  进行函数重写
public: 
    string m_msg;
    MyOutOfRange(const char* str){
        // const char* 隐士转换为string
        this->m_msg = str;
    }

    MyOutOfRange(string str){
        // const char* 隐士转换为string
        this->m_msg = str;
    }

    // virtual char const* what() const{
    //     // string无法隐式转换为const char* 需要手动转换
    //     return m_msg.c_str();
    // }

    // virtual 虚函数复写 才能实现多态, 才能运行自己复写后的程序  重载what()
    virtual const char* what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_NOTHROW{
        //  string无法隐式转换为const char* 需要手动转换
        return m_msg.c_str();
    }

};

class Students05{
public:
    int m_age;
    Students05(int age){
        if(age <0 || age > 50)
        {
            // throw MyOutOfRange("年龄0到150");  // const char*   字面量,是常量无法更改的字符串类型
            throw MyOutOfRange(string("年龄0到150"));  // 转成 string 类型后 走 MyOutOfRange(string str)
        }
        else{
            this->m_age = age;
        }
    }
};
int main()
{
    try{
        Students05 stu(1000);
    }
    catch(exception& e){
        cout << e.what() << endl;
    }
    return 0;
}

编写自己的异常类

① 标准库中的异常是有限的;

② 在自己的异常类中,可以添加自己的信息。(标准库中的异常类值允许设置一个用来描述异常的字符串)。

2. 如何编写自己的异常类?

① 建议自己的异常类要继承标准异常类。因为C++中可以抛出任何类型的异常,所以我们的异常类可以不继承自标准异常,但是这样可能会导致程序混乱,尤其是当我们多人协同开发时。

② 当继承标准异常类时,应该重载父类的what函数。

相关推荐
Larry_Yanan21 小时前
QML学习笔记(五十)QML与C++交互:QML中单例C++对象
开发语言·c++·笔记·qt·学习·ui·交互
im_AMBER21 小时前
算法笔记 09
c语言·数据结构·c++·笔记·学习·算法·排序算法
SweetCode1 天前
C++ 实现大数加法
开发语言·c++·算法
stay_alive.1 天前
C++ 四种类型转换
开发语言·c++
卡提西亚1 天前
C++笔记-9-三目运算符和switch语句
c++·笔记
CodeWizard~1 天前
AtCoder Beginner Contest 430赛后补题
c++·算法·图论
喜欢吃燃面1 天前
C++:哈希表
开发语言·c++·学习
mit6.8241 天前
[C++] 时间处理库函数 | `tm`、`mktime` 和 `localtime`
开发语言·c++
SweetCode1 天前
C++ 大数乘法
开发语言·c++
关于不上作者榜就原神启动那件事1 天前
模拟算法乒乓球
开发语言·c++·算法