【发布时间】:2018-06-29 05:57:26
【问题描述】:
我有以下代码将日期转换为毫秒:
long lond dateToMs(const char* text)
{
std::tm tm = {};
const char* snext = ::strptime(text, "%d-%m-%Y %H:%M:%S", &tm);
auto time_point = std::chrono::system_clock::from_time_t(std::mktime(&tm));
return time_point.time_since_epoch() / std::chrono::milliseconds(1) + std::atof(snext) * 1000.0f;
}
如果我有一个不存在的日期 例如:40-10-2015 12:23:45.2354,程序会显示以下消息:Segmentation fault (core dumped) 相反,我想显示类似The introduced date it's not valid 的内容。
我尝试了一个 try..catch 块,如下所示:
long long dateToMs(const char* text)
{
try{
std::tm tm = {};
const char* snext = ::strptime(text, "%d-%m-%Y %H:%M:%S", &tm);
auto time_point = std::chrono::system_clock::from_time_t(std::mktime(&tm));
return time_point.time_since_epoch()/std::chrono::milliseconds(1)+std::atof(snext)*1000.0f;
}
catch(const std::exception &)
{
std::cout << "The introduced date it's not valid" << std::endl;
};
}
但它显示相同的错误:Segmentation fault (core dumped),我必须做什么才能显示我想要的消息错误。
【问题讨论】:
标签: c++ datetime error-handling segmentation-fault try-catch