系统的标准异常类

lambdaios / 2024-01-16 / 原文

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdexcept>
class maker {
public:
    maker(int age) {
        if (age < 0 or age>150) {
            throw std::out_of_range("年龄不在范围内\n");
        }
        else {
            this->age = age;
        }
    }

    int age;
};


void test() {
    try {
        maker m(200);
    }
    catch (std::out_of_range& ex) {
        std::cout << ex.what() << '\n';
    }
}
int main(){

    test();

    return 0;
}


异常的基类与之对应的继承关系

简易的手写异常


#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdexcept>
#include<algorithm>
class myout_of :public std::exception {
public:

    myout_of(const char*errorinfo) {
        //const char* transform std::string
        this->m_info = std::string(errorinfo);
    }

    myout_of(const std::string errorinfo) {
        this->m_info = errorinfo;
    }

    const char* what()const {
        // change std::string to const char*
        return this->m_info.c_str();
    }


    std::string m_info;
    
};

class maker {
public:
    maker(int age){
        if (age < 0 or age>150) {
            //throw std::out_of_range("年龄不在范围内\n");
            throw std::move(myout_of("年龄不在范围内2\n"));
        }
        else {
            this->age = age;
        }
    }

    int age;
};


void test(){
    try {
        maker m(200);
    }
    catch (std::out_of_range& ex) {
        std::cout << ex.what() << '\n';
    }
    catch (myout_of &t) {
        std::cout<<t.what();
    }
}
int main(){

    test();

    return 0;
}