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函数。

相关推荐
Rabitebla41 分钟前
【Linux】文件篇(六):Shell 实战——从系统调用到命令行重定向
linux·服务器·c++·笔记·学习
无忧.芙桃15 小时前
C++语言原理与实践(二十三):哈希表的实现
c++·链表·哈希算法·散列表·哈希表
AvocadoZeroOneOI18 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
whitelbwwww20 小时前
cuBLAS--CUDA高性能线性代数计算库--第一部分
c++·线性代数·gpu算力·cuda c++
eggwyw1 天前
C++设计模式之解释器模式
开发语言·c++
我不会插花弄玉1 天前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴2 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus2 天前
C++ explicit 关键字工程实践
开发语言·c++
AIgorithmGEEK2 天前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
一拳一个呆瓜2 天前
【STL】头文件:<cmath>
c++·stl