• C++ 79 之 自己写异常类


    1. #include
    2. #include
    3. using namespace std;
    4. class MyOutOfRange : public exception{ // 选中exception右键 转到定义 复制一份 virtual const char* what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_NOTHROW 进行函数重写
    5. public:
    6. string m_msg;
    7. MyOutOfRange(const char* str){
    8. // const char* 隐士转换为string
    9. this->m_msg = str;
    10. }
    11. MyOutOfRange(string str){
    12. // const char* 隐士转换为string
    13. this->m_msg = str;
    14. }
    15. // virtual char const* what() const{
    16. // // string无法隐式转换为const char* 需要手动转换
    17. // return m_msg.c_str();
    18. // }
    19. // virtual 虚函数复写 才能实现多态, 才能运行自己复写后的程序 重载what()
    20. virtual const char* what() const _GLIBCXX_TXN_SAFE_DYN _GLIBCXX_NOTHROW{
    21. // string无法隐式转换为const char* 需要手动转换
    22. return m_msg.c_str();
    23. }
    24. };
    25. class Students05{
    26. public:
    27. int m_age;
    28. Students05(int age){
    29. if(age <0 || age > 50)
    30. {
    31. // throw MyOutOfRange("年龄0到150"); // const char* 字面量,是常量无法更改的字符串类型
    32. throw MyOutOfRange(string("年龄0到150")); // 转成 string 类型后 走 MyOutOfRange(string str)
    33. }
    34. else{
    35. this->m_age = age;
    36. }
    37. }
    38. };
    39. int main()
    40. {
    41. try{
    42. Students05 stu(1000);
    43. }
    44. catch(exception& e){
    45. cout << e.what() << endl;
    46. }
    47. return 0;
    48. }

    编写自己的异常类

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

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

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

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

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

  • 相关阅读:
    2023第五届中国(济南)国际中医药产业展览会(CJTCM)
    918. 环形子数组的最大和
    spring-cloud-alibaba: nacos原理详解
    设计模式-中介者模式
    Selenium安装以及案例演示【Java爬虫】
    DBus笔记
    leetcode - 438. Find All Anagrams in a String
    探索工业AI智能摄像机的高端科技
    PHP数组处理$arr1转换为$arr2
    期货开户公司受到证监会的监管
  • 原文地址:https://blog.csdn.net/LSG_Down/article/details/139811538