2

lvl是一个enum class

switch(lvl)
{
case LogLevel::Trace:
    return "Trace";
case LogLevel::Debug:
    return "Debug";
case LogLevel::Info:
    return "Info";
case LogLevel::Warning:
    return "Warning";
case LogLevel::Error:
    return "Error";
case LogLevel::Fatal:
    return "Fatal";
default:
    assert(0 && "Unhandled LogLevel in LevelToStr"); return "???";      // This one?
    throw std::invalid_argument( "Unhandled LogLevel in LevelToStr" );  // or this one?
}

共识是default应该存在的,但相关问题中的意见对于它应该做什么存在分歧。让整个事情崩溃?使当前线程崩溃?尝试优雅地处理异常?

双方在评论中提出了一些论点,但讨论并不完全有定论。

有人可以提供一个全面的答案,应该使用哪个,或者在什么条件下使用?

4

1 回答 1

2

这完全取决于您的系统的要求。

我实际上认为最好不要default:在这种情况下使用。如果你忽略它,如果你在编译时错过了一个案例,你会得到一个有用的警告。如果您使用 -Werror 进行编译,那么在您修复警告之前,您的程序将无法编译。

void handle_something(LogLevel lvl)
{
    switch(lvl)
    {
    case LogLevel::Trace:
        return "Trace";
    case LogLevel::Debug:
        return "Debug";
    case LogLevel::Info:
        return "Info";
    case LogLevel::Warning:
        return "Warning";
    case LogLevel::Error:
        return "Error";
    case LogLevel::Fatal:
        return "Fatal";
    // note: no default case - better not to suppress the warning
    }

    // handle the default case here

    // ok, so now we have a warning at compilation time if we miss one (good!)
    // next question: can the program possibly continue if this value is wrong?
   // if yes...
   return some_default_action();

   // ... do we want debug builds to stop here? Often yes since
   // ... this condition is symptomatic of a more serious problem
   // ... somewhere else

   std::assert(!"invalid log level");

   // ...if no, do we want to provide information as to why
   // ... which can be nested into an exception chain and presented
   // ... to someone for diagnosis?

   throw std::logic_error("invalid error level: " + std::to_string(static_cast<int>(lvl));

  // ... or are we in some mission-critical system which must abort and
  // ... restart the application when it encounters a logic error?

  store_error_in_syslog(fatal, "invalid log level");
  std::abort();
}
于 2016-05-09T10:03:15.073 回答