I'm trying to check if a date is valid using boost date_time
. The documentation says it will throw an exception if the date is invalid. Now I've been trying to use try-catch if the date is indeed invalid but somehow my program still gets thrown out and stops..
simple test code:
#include "boost/date_time/gregorian/gregorian.hpp"
#include <iostream>
int main()
{
int year = 2013;
int month = 1;
int day = 50;
try
{
boost::gregorian::date d(year, month, day);
throw 20;
}
catch (int e)
{
std::cout << "error! date does not excist!" << std::endl;
std::cout << "error no: " << e << std::endl;
}
return 0;
}
final question: what is the proper way using date_time to validate a date?
boost::gregorian::date
throws std::out_of_range
type exceptions when day, month or year are out of range.
Your catch block catches exception of int
type. You need to use a catch block with type std::out_of_range
to catch the specific exception.
Also, there is no need to use a throw(20)
statement in your try block.