When the constructor throws an exception, how can I prevent the creation of an object?
In the example below, I create a Month () class for which the valid values โโof the int month_ are in the range of 1 to 12. I create December or dec with an integer value of 13. An exception is thrown, as it should, but the object is still created . Then the destructor is called.
How can I abort class instantiation when an exception occurs?
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; Good eye, Nat! if ((month < 1) || 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; }
c ++ constructor exception-handling c ++ 11 try-catch
kmiklas
source share