3 ms·
You also tend to overlook/ignore the "if err != nil" in every other line, which Google seems to push. There is really no silver bullet for error handling, and s
by Noughmad 11y ago
You also tend to overlook/ignore the "if err != nil" in every other line, which Google seems to push. There is really no silver bullet for error handling, and sometimes you need more than one approach. However, I think exceptions are usually the best, especially because they work very well with RAII.
It would be great to have some function annotations to show which exceptions can be thrown, though. But still, keep in mind tha Google's style is pretty much equivalent to having a catch(...) after every call.
- sseagull 11y ago>It would be great to have some function annotations to show which exceptions can be thrown, though. There was [0]. It is deprecated and generally discouraged, since it quickly becomes a maintenance nightmare (since you have to include unhandled exceptions for all functions called from that function, etc, all the way down). [0] http://en.cppreference.com/w/cpp/language/except_spec http://en.cppreference.com/w/cpp/language/except_spec
- uxcn 11y agoException specifications (deprecated) aren't the same as checked exceptions, which I think was what some people might have in mind. In theory, they look like they solve a number of problems, but in practice they really create more than they solve. Even Java language designers have said that checked exceptions were a mistake. The noexcept keyword was actually added to address some of the limitations.
- Noughmad 11y agoI agree that these things get ugly very quickly. Another thing is that you aren't always catching all exceptions; for example, sometimes you are sure that something is in bounds, but the function is still declared as throws(out_of_range) or similar. Is there a better way to do it, maybe a static analyzer or IDE warning about possible exceptions?
- uxcn 11y agoInstead of exceptions, I personally prefer using assertions to verify things like preconditions; in which case if an assertion fails the software should generally crash before getting into a worse state. Arguably, if the software shouldn't crash it's probably not an exception. Assertions can also give an analyzer a set of preconditions to check. For example, Clang's static analyzer parses assert statements [1]. I'm not sure it uses them to verify the preconditions, but regardless it's still a good way to express them. Another way to express constraints are attributes, which static analyzers (and optimizers) also use. For example, GCC has a number of function attributes [2] to express invariants about code. [1] http://clang-analyzer.llvm.org/scan-build.html#recommended_debug http://clang-analyzer.llvm.org/scan-build.html#recommended_d... [2] https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attribute...