有分段错误时更改显示的消息错误

时间:2018-01-19 22:30:40

标签: c++ datetime error-handling segmentation-fault try-catch

我有以下代码将日期转换为毫秒:

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),我需要做些什么来显示我想要的消息错误。

1 个答案:

答案 0 :(得分:1)

您没有考虑snext为空的可能性。

long long dateToMs(const char* text)
{
     std::tm tm = {};
     const char* snext = ::strptime(text, "%d-%m-%Y %H:%M:%S", &tm);
     if ( snext )
     {
          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;
     }
     else
     {
          std::cout << "The introduced date it's not valid";
     }


}

Live sample