11 ms·
It seems silly to have to check the error return code with an if for every method I call. Surely a try { } catch around a block makes more sense than littering
by trailfox 14y ago
It seems silly to have to check the error return code with an if for every method I call. Surely a try { } catch around a block makes more sense than littering my code with if (errorHappened) in every second line.
- NateDad 14y agoHow do you know what failed, then? A try/catch around the entire function simply tells you "something failed". Often times that is not good enough in a real program. You can't handle the error, since you don't know what function call it came from, so you're probably just logging it and swallowing it. It also means that you don't know how much of your code executed. Have you written that file to disk yet? Maybe you need to clean it up now? Is that socket still open? or maybe you didn't get that far in the code? In code that cares about handling errors, you end up with a lot of try/catches around individual functions that you know can throw... this is no different than go's if err != nil code. try { v = ThisCanThrow() } catch (Exception ex) { // handle this specific failure } v, err := ThisCanError() if err != nil { // handle this specific failure } Because Go forces you to handle the error at the site where it is produced, error handling ends up being much more robust and specific. You can't just "let 'em fly" and make someone else deal with random exceptions up the stack. This almost always produces better code in the end. Believe me, I understand where you're coming from. I've been using exceptions for 13 years in production code. I initially skipped Go pretty much solely because of the lack of exceptions. But I am really glad I gave it a second chance, because, damn, it is good.
- trailfox 14y agoThanks for the explanation. In most cases cleanup is handled in finally blocks and the unit of work fails if any of N calls fails, in most case it makes no difference which one failed. Where the difference does matter it's probably in a different method etc. Your explanation does seem to make the case for this type of error seem somewhat sensible, maybe I'll give Go another try. Are methods which return errors and the types of errors returned clearly documented/visible?
- carbocation 14y agoMethods' declarations indicate which ones return an error value. E.g.: func Demo (s string) (string, error){...} When called, that is guaranteed to return a string and an error value (OR nil).
- drbawb 14y agoThis is a fairly minor point: but I also like how idiomatic error handling in Go only indents the block that handles the problem. Because of multiple returns, the normal flow of execution isn't indented. I find that this makes it easier to skim Go code in practice.
- redbad 14y agoIt seems silly, but it's simple, powerful, and removes a large class of ambiguity from your programs.