mardi 28 mai 2019

C++ class exceptions overriding const char* what() const throw () method

I'm having some difficulties learning exceptions in c++. I have a simple class named Clothing and a custom exception class named WrongClothingSize. I want the exception class to throw something like "WrongClothingSize exception! Size is unacceptable, Size: xxx" in the console, when i try to make a Clothing object of a non-existing size (example: male clothing size: 95) in the main file. I will also include some details in TODO comments in parts of my code. Thank you for your time!

Clothing.cpp

//TODO add throw where necessary
Clothing::Clothing() :
        name("unknown"), gender(0), size(0), price(0) {

}

Clothing::Clothing(string name, int gender, int size, double price) :
        name(name), gender(gender), size(size), price(price) {

}

Clothing::Clothing(const Clothing &object) :
        name(object.name), gender(object.gender), size(object.size), price(
                object.price) {
}

Clothing::~Clothing() {

}

int Clothing::getSize() {
    return size;
}

void Clothing::setSize(int c) {
    size = c;
}

WrongClothingSize.h

class WrongClothingSize: public std::exception {
public:
    WrongClothingSize();
    const char* what() const throw () { //abstract function from exception header
        return msg.c_str();
    }
    virtual ~WrongClothingSize();
    /*TODO check if size of clothing is acceptable (correct)
     * Example:
     * bool Clothing::isSizeValid(int gen, int siz) {
    if (gen == 0){
        if (siz == 46 || siz == 48 || siz == 50 || siz == 52 || siz == 54 || siz == 56)
            return true;
    }
    else if (gen == 1){
        if (siz == 32 || siz == 34 || siz == 36 || siz == 38 || siz == 40 || siz == 42 || siz == 44 || siz == 46 || siz == 48 || siz == 50 || siz == 52 || siz == 54)
            return true;
    }
    return false;
}
     */
private:
    const std::string msg;
};


WrongClothingSize.cpp

#include "WrongClothingSize.h"

WrongClothingSize::WrongClothingSize() :
        msg("Wrong Clothing Size!") {

}

WrongClothingSize::~WrongClothingSize() {
    // TODO Auto-generated destructor stub
}

Aucun commentaire:

Enregistrer un commentaire