switch()中未处理的枚举类值-异常或断言

Unhandled enum class value in switch() - Exception or Assert?

本文关键字:异常 断言 枚举 未处理 switch      更新时间:2023-10-16

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应该存在,但在相关问题上,人们对它应该做什么存在分歧。搞砸整件事?使当前线程崩溃?尝试优雅地处理异常?

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

有人能给出一个全面的答案吗?应该使用哪一个,或者在什么条件下使用?

它完全取决于系统的需求。

实际上,我认为在这种情况下最好不要使用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();
}