出现分段错误时,更改显示的消息错误



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

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 .我试过了..捕获块如下:

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),我必须做什么才能显示我想要的消息错误。

您没有考虑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";
     }

}

现场样品

相关内容

最新更新