我正在尝试使用boost date_time检查日期是否有效。 文档说如果日期无效,它将抛出异常。 现在我一直在尝试使用try-catch如果日期确实无效但不知何故我的程序仍被抛出并停止..
简单的测试代码:
#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; }最后一个问题:使用date_time验证日期的正确方法是什么?
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在日,月或年超出范围时抛出std::out_of_range类型异常。 catch块捕获int类型的异常。 您需要使用类型为std::out_of_range的catch块来捕获特定的异常。
此外,您不需要在try块中使用throw(20)语句。
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.
更多推荐
发布评论