提升日期时间捕获异常(boost date time catching exception)

编程入门 行业动态 更新时间:2024-10-25 06:23:39
提升日期时间捕获异常(boost date time catching exception)

我正在尝试使用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.

更多推荐

本文发布于:2023-07-04 10:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023525.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   日期   时间   boost   exception

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!