That's how mistakes are made when handling errors
so this... try { f := OpenFile() try { f.Write("foobar") } catch { log.Error("write failed") } } catch { log.Error("open failed") } is easier to you than this? f, err := OpenFile() if err != nil { log.Error("open failed") return } if _, err := f.Write(); err != nil { log.Error("write failed") }
This is not a good example imo
Maybe but if we agree on some interface for the thrown error (error code or something) we can have much less code doing more. I get it that go make it easier to recognize the origin of the error that way but it does affect amount of code I am writing as a developer.
it's not, sure, but still, try-catch is a very ugly construct IMHO
The example u gave for traditional approach is kinda unfair imo. if all the functions that might throw and error followed a similar pattern in the error they throw, I will have one try catch.
And precisely why try catch is dangerous
how do you determine which Write call failed without having separate try-catch blocks?
yeah maybe go is less evil that way now that i think about it. i am just not used to 20 lines functions i guess 😝
Well in most cases I won't care as long as the error thrown provides enough data about itself. let's say a register user function that calls: validation method, database method. if both method will throw the error with a message and code in it, I will just want to return it. Idc where it failed.
what if they don't throw any codes? (happens a lot actually)
then the methods are badly implemented, which i realize is what go is trying to protect u from doing.
If you use try catch as if err.. are terrible, if you use in smarter way are very elegant. IMO in several situation go is verbose in error handling, some piece of code I wrote there is more error handling boilerplate than code logic. With try catch, used in the proper way (not as in this example) the whole solution could be more readable and compact. Nevertheless the go error handling has other advantages
Обсуждают сегодня