switch()中未处理的枚举类值-异常或断言
Unhandled enum class value in switch() - Exception or Assert?
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();
}
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- STD :: Future no_state异常与断言
- 值传递、异常/断言和类设计.批评/问题
- switch()中未处理的枚举类值-异常或断言
- 如何断言未引发异常
- 我们应该在C++单元测试中测试src代码断言(NOT异常)吗
- Ffmpeg断言-抛出异常而不是中止
- c++错误代码与断言与异常的选择
- 异常vs断言的科学计算家伙(我是我的代码的唯一用户)
- c++断言函数,检查是否抛出异常
- 断言失败/STL异常
- 如何使STL抛出异常而不是断言