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

相关推荐
mit6.8242 小时前
[实现Rpc] 通信类抽象层 | function | using | 解耦合设计思想
c++·网络协议·rpc
laimaxgg2 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
ox00805 小时前
C++ 设计模式-命令模式
c++·设计模式·命令模式
Blasit5 小时前
C++ Qt建立一个HTTP服务器
服务器·开发语言·c++·qt·http
..过云雨6 小时前
04.类和对象(下)(初始化列表、static静态成员、友元friend[类外函数使用类私有成员]、内部类、匿名对象等)
开发语言·c++
刃神太酷啦6 小时前
树(数据结构·)
数据结构·c++·蓝桥杯c++组
清水加冰6 小时前
【算法精练】背包问题(01背包问题)
c++·算法
Mr.kanglong9 小时前
【C++】智能指针
开发语言·c++
不灭锦鲤9 小时前
c语言(函数)
c语言·c++·算法
Unique_yt9 小时前
02.19 构造函数
开发语言·c++·算法