问题
I know this is subjective, but should exceptions be caught in the lowest level or higher. I ask because I usually do
try
{
//..
}
catch
{
//LOG
}
So when I implement some "low level" function, like
std::string read_from_file(const std::string& file_name);
Im not sure what should I do:
1) let caller handle exception.
2) catch (log?) and rethrow
3) catch and change function so that bool is return type(last line in try is return true; last line in catch is return false;). I dont like this but Ive seen it done many times.
4) ???
回答1:
Catch at the level that can truly handle it or when there is no other place to throw it.
Catching and rethrowing doesn't handle anything, unless your purpose is to wrap an exception in something more illustrative (e.g. Spring persistence wraps SQLException into something more meaningful by looking at SQL error codes).
Sometimes there's no place else to go. No user should ever see a stack trace, so controllers should catch everything and redirect to a friendly error page.
You can catch and change return type, but users are losing information. "true/false" won't tell them the same info as a stack trace. Sending back "success" for a caught exception doesn't feel right to me.
If you can't handle an exception, bubble it up to a layer that can. If you can handle it, do so.
来源:https://stackoverflow.com/questions/10977482/at-what-level-and-how-is-appropriate-to-catch-exceptions