vendredi 30 juin 2017

How to prevent constructor from creating object when exception is thrown

When a constructor throws an exception, how can I prevent the object from being created?

In the example below, I create a Month() class, for which legal values of the int month_ property are in the range of 1 to 12. I instatiate December, or dec, with integer value 13. The exception is thrown, as it should be, but the object is still created. The destructor is then called.

How do I abort creation of a class instance upon a thrown exception?

OUTPUT

-- Month() constructor called for value: 2
-- Month() constructor called for value: 6
-- Month() constructor called for value: 13
EXCEPTION: Month out of range
2
6
13
-- ~Month() destructor called.
-- ~Month() destructor called.
-- ~Month() destructor called.
Press any key to exit

Minimal, complete, and verifiable example

#include <iostream>
#include <string>

class Month {
public:
    Month(int month) {
        std::cout << "-- Month() constructor called for value: " << month << std::endl;
        try {
            if ((month < 0) || month > 12) throw 100;
        } catch(int e) {
            if (e == 100) std::cout << "EXCEPTION: Month out of range" << std::endl;
        }
        month_ = month;
    }
    ~Month() {
        std::cout << "-- ~Month() destructor called." << std::endl;
    }
    int getMonth()const { return month_; }
private:
    int month_;
};

int makeMonths() {
    Month feb(2), jun(6), dec(13);
    std::cout << feb.getMonth() << std::endl;
    std::cout << jun.getMonth() << std::endl;
    std::cout << dec.getMonth() << std::endl;
    return 0;
}

int main() {
    makeMonths();
    std::cout << "Press any key to exit"; std::cin.get();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire