c++ - 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 "???";      // one?     throw std::invalid_argument( "unhandled loglevel in leveltostr" );  // or one? } 

the consensus default should there, opinions in related question divided on should doing. crash whole thing? crash current thread? try handle exception gracefully?

the sides present arguments in comments discussion isn't quite conclusive.

could present comprehensive answer 1 should used, or in conditions?

it depends on requirements of system.

i argue it's better not use default: in case. if leave out, you'll useful warning if missed case @ compile time. if compile -werror program fail compile until you've fixed warning.

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 suppress warning     }      // handle default case here      // ok, have warning @ compilation time if miss 1 (good!)     // next question: can program possibly continue if value wrong?    // if yes...    return some_default_action();     // ... want debug builds stop here? yes since    // ... condition symptomatic of more serious problem    // ... somewhere else     std::assert(!"invalid log level");     // ...if no, want provide information why    // ... can nested exception chain , presented    // ... diagnosis?     throw std::logic_error("invalid error level: " + std::to_string(static_cast<int>(lvl));    // ... or in mission-critical system must abort ,   // ... restart application when encounters logic error?    store_error_in_syslog(fatal, "invalid log level");   std::abort(); } 

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -