190 points · by progapandist · 8y ago · 177 comments
The approach suggested for Go 2 under bargaining is basically a reverse try-catch at best and a Visual Basic “on error goto” at worst.
Even in their own attempt to explain why try catch is bad they effectively admit it serves a common use-case: A common use-case not handled by Go no less.
This lacking also puts the burden on the programmer which will have to manually handle each and every error, by himself, everywhere, one by one.
Even worse are the priorities given in the language: checking for errors is cumbersome, while ignoring errors is easy.
I’m willing to be proven wrong, but my immediate guess is that this in general leads to more buggy code, not less.
https://github.com/golang/go/wiki/Go2ErrorHandlingFeedback
and this broad survey of error handling requirements:
https://gist.github.com/networkimprov/961c9caa2631ad3b95413f...
Also the author overlooks the Error Values draft design, which is tentatively targeted for Go 1.13:
https://go.googlesource.com/proposal/+/master/design/go2draf...
Trade-offs for whom or with what in mind? the compiler or the programmer?
That's the "philosophical" difference between the Rust team and the Go team.
Even with two wildly different approaches to language design, each has their place, and their own set of drawbacks.
There's also a recommended way of dealing with errors. I may not state it correctly but basically you build a pipeline of operations for a data type that represents the arguments (or data) of the operations. For example, to compress an image given a URL:
type Image struct {
src string
bytes []byte
width uint
height uint
err error
}
func NewImage(src string) Image {
return Image{src: src}
}
func (img Image) Get() {
if err != nil {
return
}
...
// Set error value if this operation fails
}
func (img Image) Compress {
if err != nil {
return
}
...
// Set error value if this operation fails
}
func (img Image) Err() error { return img.err }
img := NewImage("https://image.src/random-image.png")
img.Get()
img.Compress()
if img.Err() != nil {
// handle error just once
}What are some cases where errors can be ignored? And if they can be, are these neccesarily some sort of "status" rather than "error"?
How likely is the error going to happen, if you know (through tests and everything) that the query is correct?
it can only happen in two scenarios:
1. the database has serious problems 2. the driver is incorrect
in normal cases you would probably handle that with a middleware in classical languages. i.e. you would have a middlewre that catches exceptions and handle the error there (logging, paging, whatever) and maybe show a nice looking "we are experience problems now"-page.
in golang this is a little bit harder, since you would need to handle the error by every caller and with the default http interface you would actually need to call your "handle default error" in every http handler.
https://blogs.msdn.microsoft.com/oldnewthing/20050114-00/?p=...
https://blogs.msdn.microsoft.com/oldnewthing/20040422-00/?p=...
While forceful, I don't accept the conclusion of Raymond's argument. I feel it may be true for programmers primarily trained and experienced in C, but is not true in general. As such, the argument reduces to "programmers who are not familiar with exceptions sometimes make mistakes when using them." One could say the same thing about pointers, dynamic typing, lambdas, macros, comprehensions, pass-by-reference, etc. Today, most programmers are familiar and comfortable with exceptions, having almost certainly been taught to use them in college and almost certainly using them on a daily basis for their entire professional career. They'll also have been taught to use a language-specific toolbox such as RAII or try/catch/finally to deal with any potential problems.
Once you get in the habit, it's not hard to scan through a program line-by-line asking yourself "what would happen if an exception were thrown at this point?" and to take appropriate precautions. In fact, I'd wager that for anyone who's spent years working in any language with exceptions this quickly becomes second nature. It's also an easy way to add value during peer code review. In my experience, writing correct code with exceptions is not "really hard," as Raymond argues, but rather no harder and a lot quicker that using explicit error handling. The reason it's a lot quicker is because "exit the function with an error status and do local cleanup of variables initialized so far" is by far the most common correct action. And for cases when its not, the try/catch/finally or other exception handling whatever is straight forward to write and no uglier than explicit error handling would have been. Of course, it's possible I think this because I've worked in languages with exceptions for most of my career. But I certainly don't observe that even the most junior programmers on my team create a ton of bugs that could be attributed to mishandled exceptions. In fact, I can only remember a handful of such bugs, mostly involving open database transactions or unhelpful error messages masking more detailed error messages.
A more solid objection to language support for exceptions can be made by pointing out all invisible code generated by the compiler to correctly handle exceptions. This can lead to significant code bloat and in some cases can negatively impact performance. Or by pointing out how unwise it is to be allocating additional Exception objects while dealing with out of memory errors. These are some of the reasons why C++ isn't appropriate for an OS kernel, for example.
I feel there's a serious disagreement here with how I tend to look at things. I don't want to look line-by-line and ask what would happen in case of an exception. In most cases the answer would be: That would be bad, since the rest of the code would not get executed and the program would remain in an invalid state.
It's much easier to know that there will not be an exception. Simple sequential code, the way it was intended to be by the ancient gods. And handle errors manually where they could in fact occur. I reckon that for my own code, that is only once in a hundred lines or more. Or maybe even more (lines) than that, since I'll abort directly in the callee in many cases anyway, so the caller never gets a chance to see the error. But if there were any point in handling an error in the future, we can still switch to handling it later.
Now you can argue that you can do that with exceptions as well (handling errors directly either by returning an error code or by aborting) such that exceptions would never bubble up. But in that case what's the point in exception handling to begin with? It's just the same now, except that there's a lot of exceptions machinery required in the language.
Simple? Additions may overflow, printf may fail, etc. Usually code looks simple only because it ignores errors..
As for sequential, we're in the age of multiple cores and GPUs..
But this is only ever possible if the program moved to an invalid state in the first place. Granted, sometimes there is no way around that, but usually it can and should be avoided.
I once implemented a C++ class where some member functions implemented the strong exception safety guarantee. I can tell you, yes it really is that hard. Even when you know certain variables are pointers and can't throw, you are tiptoeing around on razorblades.
At my day job we use exceptions in Java a lot, and it's a good abstraction for rolling back database transactions. But for non-transactional code it isn't the best.
If you're mentally comparing against the way error handling in C, your position is much more defensible. Error handling in C requires manually releasing resources in the correct order, and it's easy for a destructor to slip by in the wrong order, to get missed entirely, or for someone to use the wrong jump label. (I'm thinking about Linux kernel style code, here.) If I'm reviewing some error handling code in C, I might have to scan up to the top of the function and count all the resources which need to be released, then look down to the bottom to see that the right label is being jumped to. That's a pain.
In languages like Golang, error handling and resource cleanup are a bit more orthogonal. You can look at a Golang call which returns an error and ask, "Does this handle the error correctly?" Usually this only requires looking at three lines of code at a time, maybe four. Resources are just released with defer, except in unusual cases.
> Once you get in the habit, it's not hard to scan through a program line-by-line asking yourself "what would happen if an exception were thrown at this point?"
I guess I never got in the habit. Maybe you have better habits than I do, or maybe I'm just not "smart enough" to be a programmer, but I find this hard, so I choose to use languages which make this easier. I find it hard in Python, hard in JavaScript, hard in C++, and hard in C#. I'm really not even sure how to e.g. handle exceptions thrown by C++ constructor failures separately from other things later in the block, e.g., I want to do this:
try {
MyType x{args, args};
} catch (SomeException &e) {
...
}
x.DoSomething();
And I'm not sure how to even write this as functional C++ without doing something weird or maybe just saying "fuck it" and wrapping x in std::unique_ptr.> In fact, I'd wager that for anyone who's spent years working in any language with exceptions this quickly becomes second nature.
Based on what I see during code reviews, I don't agree. Raymond Chen has a good point... when I review someone's Golang code, checking for correct error handling is fast and easy, it's mostly mechanical, easy to target with lint, and I can immediately move on to looking at the code semantics. With, say, C# code, or especially Python code, there are too many cases where a method call slips inside or outside the try/catch block where it belongs.
I've also been bitten too many times by bugs in production where a function throws an exception, and we have to decode the stack trace to figure out what the error means or how the error is even possible. This is typically easier in programs written in Golang, at least in my experience.
The more syntactic sugar a language has, the more likely it is that I don't notice an error condition that is being handled incorrectly. Golang, with its simplicity, makes you do some extra typing up front but in my experience it pays for itself by going faster through code review and bug fixes.
This depends on the kind of code you're writing. If you're mostly sticking inside application memory and not doing, e.g., IO, IPC, etc, then the exception approach is better.
I'm not saying Golang is perfect by any means, but I find the way it does error handling to be a welcome reduction in my cognitive load.
try {
MyType x{args, args};
x.DoSomething();
} catch (SomeException &e) {
...
}
You can't do much with the x if it didn't construct correctly, so you either need a strategy for a safe default value for x, or you need to bail entirely if an exception occurs.> In imgproxy, I use this approach to stop image processing if the timeout is reached (see here, and here). The goal is not to bother about returning timeout errors from each function
(emphasis mine)
While I understand the pain, I do not like the train of thought. It is our duty as responsible developers to bother with error handling. Luckily this is not a library but a "standalone application", not a "library", which is a slightly different use case (e.g negroni has to recover from panics to log and continue serving http requests).
The accepted solution looks like† a world of pain waiting to blow up in a myriad of subtle corner cases (do you remember what happens exactly when there's a panic in a defer that was called because of a panic, and in which order deferred functions are called?) and is barely more readable. I've seen much more interesting and obviously robust Go 1 patterns (that I can't find right now) that e.g pass error handler functions around.
† At first sight. Maybe it's not when digging deeper, but that's not the point: the most glorious thing to me when I read idiomatic Go code is that basically everything is boringly obvious. This is a clever hack and crosses a threshold I'm not willing to go past in production-class code.
The syntax could be better (I do have err, !=, and nil keys on my keyboard, I really do) and it would be nice to annotate errors and not lose the semantic information (fmt.Errorf("trying foo: %v", err) throws away the specifics of err beyond the result of err.Error()), but really... explicitly handling errors after every function, even if it's just "return err" and punt to the code one level up... is something you have to do in every language. Go just front-loads it.
As for timeouts, I am not sure why you wouldn't just pass in a context, which already has provisions for a deadline, explicit cancellation, and cancelling further library calls. If you can cancel your operation when <-ctx.Done() returns, then you can ensure that all the related work is cancelled. You don't need a clever panic/recover for that. Just select { case <-workDone: ...; case <-ctx.Done(): cancelWork(); return ctx.Err() }. I am not sure why people rely on hacks when there's already a standard method built into the language.
C, like Go, convinces people they handle errors. And then, when you look into what that actually means, correctly handling error cases for even trivial problems ... you immediately find out "nope, you're not handling errors, you're ignoring them". C, and Go are very sneaky that way.
1) one of the more common error cases is nil, closely followed by out of memory and zero division ... which in Go causes a panic just like every other language.
So your Go error handling in this case is never going to be executed. If you think you can avoid exceptions, you're lying to yourself. Every last method needs to be ready that a panic gets called at almost any point. Which ... is exactly what the error system was supposed to fix.
2) "If you treat them as "exceptions" rather than the rule, then you will just write flaky software ..."
This sounds nice until you look at Go sources on github. And you see WHY they're not flaky. Do people handle errors more in Go sources than in Java ? The reverse is true !
But Go software is more stable. How can this happen ?
Well, Go defaults to ignoring errors and just continuing whereas Java (and every sane language) defaults to aborting the program rather than letting it run in an unknown state.
To put it more extreme, and more to the point Go just starts "sudo rm -Rf /" when an error happens. The reality is that Go programs just start writing things to the database based on wrong information when an error happens.
3) "As for timeouts, I am not sure why you wouldn't just pass in a context, which already has provisions for a deadline, explicit cancellation, and cancelling further library calls..."
Again, this sounds cool. You can recognize code that actually uses this correctly.
Incorrect (in more ways than one):
if _, err = f.Write(something); err != nil {
return err
}
More correct: var err error
cont := true
for retry := 0; cont; retry++ {
if retry > max_retries {
return fmt.Errorf("couldn't do X in max retries. Last error was: %v", err)
}
didit := make(chan bool)
go func() {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("the call panicked: %v", r)
}
didit <- true;
}
n := 0
for n < len(something) {
i, err = f.Write(something);
if err != nil {
return
}
n += i
}
}
select {
case <-didit:
// Ok, go to next statement
if err == nil {
cont = false
}
case <-ctx.Done():
return fmt.Errorf("context signaled abort")
case <-time.After(timeout):
}
}
Have you seen such a code style ... even once ?And what will this do ?
f.Write(something)
One of 5 things:1) it may actually work (one hopes, the common case)
2) it may not write anything
3) it may PARTIALLY write what you asked to be written (including not writing anything at all and returning EAGAIN, which is why the retry logic is not really optional. Frankly you should have a higher max_retries, and ignoring for the EAGAIN case to avoid some very rare circumstances)
4) it may panic
5a) it may block for a long time
5b) it may block forever (and even make your program unkillable. I mean, we've all used NFS, right ?)
What will be your total amount of material to diagnose this problem when it occurs in cases 1-3 ? Nothing whatsoever.
Case 4 ? A large collection of stacktraces. Thankfully usually with the relevant one on top.
5a and 5b ? 100 stacktraces, when you finally kill it (or ... well Go "supports hundreds of thousands goroutines"), one of which is relevant. Well the truth is that it may actually have so many goroutines that it ... well I managed to run out of diskspace once. But it's easily 10 megabytes and more in a real webserver.
That would be safe in a language which uses exceptions or something similar or in a language where the type checker forces you to do something with the return value but Go has this odd mix of learning from C and ignoring its most important lessons and treats ignoring errors as less of a problem than an unused import. Simply having an implied if-error-than-panic check any time someone assigns a value which is never checked would go a long way towards turning subtle hard-to-debug failures-at-a-distance into clear failures at the source.
Edit: none of the examples on the golang.org homepage handle errors. You appear to have to go into the fourth section of the language tour to find error handling first being discussed 19 pages into the ”Methods and interfaces” section to find error handling discussed at all and even after that point I only saw a couple of subsequent lessons where this looked like a thing which every working developer should be routinely handling (i.e. the web crawler acknowledges that fetching network resources can fail).
I think recover() is basically almost always wrong, except around libraries that are written incorrectly and panic instead of returning errors for recoverable faults. (panic("your password is incorrect")). Writing to a closed channel or indexing off the end of an array is not a runtime error, but an error in the design of the program. I am not sure what you are saving by keeping the program alive.
So for your example, I think you are basically correct that that's what things should look like. Kill the defer/recover and let the context control the timeout. If you want to try things 3 times and have it either succeed or timeout, I don't see what choice you have but to have a for loop with 3 iterations and something that waits for the result or the timeout.
Perhaps what people want is a library that handles all failures correctly so that they don't see the possible ways things can go wrong. That's a worthy goal and I encourage people to try. In the original article, it sounded like that's what the author wanted, and his solution was to return errors out of band and have "something else" "handle them" "later". Let me know how that works out for you. If only it were that easy!
Just FYI, out of memory is Go doesn't cause a panic. It is a fatal error which is unrecoverable and will crash the whole program.
BTW, your "More correct" version code is hilarious and very not professional.
IIRC, contexts weren't added to the language until fairly late. Some people + projects got used to various degrees of homebuilt ad-hoc contexts.
And then I started learning Rust for embedded development. I basically love the entire language, and there are very, very few design decisions I disagree with.
The error handling story is much better there, and if they're making breaking changes in Go 2.0, I'd suggest they look there for a better path forward.
> Panic-Driven Error Handling
I'd insert a gif of Vader at this point, from the end of Episode 3.
I strongly disagree with this, using 'panic' should be a last resort in most situations, when the program has no reasonable way to recover from an error condition. File not found, user error, etc. are all common occurrences which should be handled by the normal mechanisms. And this goes double for library code.
The other popular criticism of Go's error handling is that it's verbose, which I wholly disagree with--the verbosity is such a negligible cost that I would much prefer verbose error handling to the language complexity required to elide them (especially if the proposed sugar required baking "errors" into the language as opposed to treating them like any other data).
The Go culture does suffice, but the Rust culture is even stronger here. Everyone is expected to use Result for something that can fail, which I like a lot for consistency's sake.
> The other popular criticism of Go's error handling is that it's verbose, which I wholly disagree with--the verbosity is such a negligible cost that I would much prefer verbose error handling to the language complexity required to elide them (especially if the proposed sugar required baking "errors" into the language as opposed to treating them like any other data).
Six months ago I would have agreed with you. And then I learned about error propagation using the question mark operator in Rust:
https://doc.rust-lang.org/book/second-edition/ch09-02-recove...
Arguments can be made about creating custom error messages at each call level, but is that really necessary most of the time?
Actually, one of the things that has prevented Go from "simply" or "just" solving the error propagation problem is precisely the recognition that in real code,
if err != nil {
return err
}
becomes problematic at scale, because it obscures the history of the error. Stack traces are great for humans, but not terribly useful for programmatic interpretation. Personally, I still tend to use "if err != nil { return err }" as my sort of default sketch implementation, but I find it is very common for many of those to grow something else before the program ships, and I'm still not all that great or consistent about layering errors properly anyhow.I'd suggest to a lot of people that it may be worth reading or re-reading the Go 2 error proposal [1], and to try to come at it with some relatively fresh eyes, rather than reading it for "does this precisely conform to my preconceived notions about what error handling should be?" (Another interesting aspect is around providing some base API for errors, and processing composite errors, rather than expecting end-users to do all the definition [2]. Personally I consider both important.) There is some legitimately interesting discussion and work around what to do, based on waiting to gather a lot of data about error handling before just slamming a solution into place, moreso than may meet the eye. I can't speak to Rust's solution in practice, but having used Haskell for a long time with union types for errors, I can say they are hardly error-handling nirvana there. If I'm reading the Rust documentation correctly, they're going to have the same problems in Rust as they do in Haskell.
[1]: https://go.googlesource.com/proposal/+/master/design/go2draf...
[2]: https://go.googlesource.com/proposal/+/master/design/go2draf...
No, this is not necessary most of the time, and I don't consider the "custom error messages" argument to be a very good argument against sugar. The convincing argument in my mind is that unlike Rust, Go has no trait system to facilitate this sugar, so the alternative is to special-case the compiler to support the error type. Of course, Go could implement a trait system, but "error handling sugar" is a negligible factor in whether or not such a system should exist and how it should be designed.
TL;DR--what makes sense for Rust may not make sense for Go.
Rust's "language complexity required to elide them" is quite literally a single postfix operator, which was added as an alternative to a small macro whose behaviour had proved wildly popular.
I disagree that the postfix operator is the primary language feature allowing rust's error handling. There is also the Result, aka a Generic Sum Type.
Go does not have generics or sum types, so it can't easily implement the generic 'Result<T, E>'. There's more to this than a bit of sugar.
Note that go does not have a generic "Into" either, which is a godsend for rust's errors.
in my book, this is not a good thing but a very bad thing.
If I'm a library function somewhere all the way down the stack and I'm at a point where something about the state I'm working on isn't up to the specification I expect them to be, then I'd prefer the safety of blowing up.
I don't want to be responsible for my callers eventually ignoring my error code and happily churning along thinking that I have fulfilled my promise and enacted the side-effect I promised to have.
If something else, far removed from me depends on me to having had the side effect, it might blow up. Or it might write corrupt data. Suddenly a thing that went wrong at one place blows up at a totally different place which makes it incredibly hard to debug.
And if the world is burning, "hard to debug" is about the least wanted property a problem could have.
Oh no. If the world is burning for me, then I absolutely do not want to continue.
But I also do not want to abort the daemon process I'm being hosted in because that would mean affecting other threads of execution (be it threads, coroutines or whatever else) where the world might be in a totally acceptable state.
Calling `exit` in a library function is outright rude.
If I get to `throw`, I can make absolutely sure that I made it clear to my caller or my caller's caller that I panicked while there's still a chance for my parent daemon to not die but handle my panic cleanly. Or, my caller, or its caller was prepared for me failing and can chose another way out.
But by throwing I can raise a very strong signal that something is wrong and I have the guarantee that if I'm being ignored, then I will kill my parent which is totally their fault for ignoring me and it will be very obvious what happened, why it happened, and, above all, where it happened.
If I'm an engineer wearing my devops hat, I'd much rather debug an uncaught exception causing a stack trace to be logged in sentry.io (or whatever else you use. I'm a very happy sentry customer, but your might have your own tool) rather than corrupted data that might have been corrupted months ago.
Your whole reply is a straw man. The author is claiming that nothing explodes b/c the error is correctly handled, not b/c it was silently swallowed.
I've seen so many bugs caused by exceptions being silently swallowed in other threads. Exceptions are not a silver bullet here, and you end up having to pass errors as values across call stacks anyway.
Yes, but I think that this is exactly what pilif is objecting to: the fact that there is no way for the callee to force the caller to deal with the error condition (I'm not sure that this is entirely correct, given that Go has the panic/recover keywords that are later discussed in the article, but then you might as well use exceptions).
IMO, this is very similar to what happens with use-after-free and other types of memory reference errors: they are extremely hard to debug because the symptoms/results of the error can be totally disconnected from the original source of the error, in some cases by minutes or longer. You simply don't want to have a situation where improper state is allowed to linger and further pollute/corrupt any subsequent computations.
Discriminate between the error-kernel of the program and the rest. The kernel is the part which is not allowed to fail. Goal: keep it small.
Discriminate between errors you have seen happen, and everything else. Handle the errors you've seen. It looks a bit like Go's handling, but only for things where you know you have an error flow. There are also exceptions, but they are somewhat rarer in typical code.
On an unhandled error, crash the isolated process. This produces, a state of the memory, a stack trace and eventually the last few messages sent to that process.
The system has a recovery model which will restart failed processes from a last known good state.
The programming language is functional, and quite much so, so there are orders of magnitude fewer errors relating to state manipulation.
One typical approach is to use the crash as a way to learn about errors that can happen, then patch those errors by handling them. Because you have a strategy for reactively handling errors, it is far less dangerous to have them in th e program, as long as they are under a noise floor.
On the other hand, the fact that we are returning a tuple of (result, err) where by convention err should be nil if everything worked screams as a terrible design to me.
But I might be influenced by reading too much Haskell/ML inspired languages :D
Once you understand applicative validation [1] or exhaustive pattern matching on row-polymorphic sum types [2], other error handling methods just seem so crude :)
[1] https://leanpub.com/purescript/read#leanpub-auto-applicative... [2] http://keleshev.com/composable-error-handling-in-ocaml
If you do a code search for Go projects on Github, a disturbing number of them get this utterly wrong, and simply do something like this:
for {
c, err := r.Read(buf)
if err == io.EOF {
break
}
if err != nil {
return err
}
...
When they should be doing something like: for {
c, err := r.Read(buf)
if err == io.EOF {
if c == 0 {
break
}
} else if err != nil {
return err
}
This is an unfortunate API design, because almost all error-returning functions have disjoint return values, and would could be expressed as sum types in other languages, which teaches developers to not expect both return values to be valid at the same time. It certainly surprised me.The other problem with Go's design is that you have to read the documentation to understand what the semantics of a particular function are. The type system can't tell you.
The same machinery still works and it's pretty straightforward to convert between the two representations (so you can track which parts of your code bail out at the first error and which parts try to soldier on).
See for example http://hackage.haskell.org/package/these or https://typelevel.org/cats/datatypes/ior.html or https://github.com/purescript-contrib/purescript-these
For a lot of FP languages that take this approach to errors you'll have three representations (bail out at first error, continue on nonfatal errors, and bail on any error but first try to accumulate as many errors as possible as a batch) that all have conversions between them depending on what you want the semantics of that section of your code to be.
And even in ML-style language, I wouldn't like a result of
(Maybe result, Maybe error)
and I would much prefer
Result result | Partial (result error) | Error error | Nothing
These two things are the same. I still like the spelled-out version better. Especially because this gives me easier way to model different things.
Consider changing my example to
Result result | Partial (result error) | Error error
or
Result result | Error error
Semantic of every one of these is different. And nicely explicit :)
>> It makes sense always to check the documentation to find out whether an error type is a part of the function signature.
O_o. So on the one hand you don't know if a function will throw an exception and can't rely on the docs, while on the other you don't know if it will return an error code so you should check the docs.
I don't write Go yet, although I look at a fair bit of it. A friend of mine who works a lot in it tells me he was put off at first but basically decided to trust the language's idioms for now. Until I have more personal experience my outlook is: "man, I think I would really miss exception handling" with a smattering of "boy that sure looks more error prone to me."
Otherwise...
I have been writing Go for about 6 years... errors make so much sense to me. Why have some external codepath for "file not found"? Why is that different than "name == bob"? They're just data that is in one state or another. You check for them the same way, with an if statement. There's nothing magical.
EDIT: This isn't some language partisanship; it's my observations from years of experience with the aforementioned languages (I work in a Python/JS shop). I'm guessing there are no formal data about this, so I'd be curious to hear other anecdotes whether they agree or conflict with mine.
It's using `vw` font measurements (instead of `px`/`rem`).
Personally, I don't like them in my editor either, but if you want to use one that's fine. But they're pretty confusing when encountering in code online.
see
https://go.googlesource.com/proposal/+/master/design/go2draf...
Is it the lack of forced stacktrace that makes flow control through exception more palatable?
Do people just like convention over compiler enforced correctness?
Or is my understanding incorrect and devs don't really like go's error handling?
Maybe I don't understand the correct go implementation.
In Java, declaring a method to throw any Exception (or should it be Throwable?) is considered an antipattern and most people use subtypes. I think if the exception hierarchy were simpler so that most of the time, there are only two kinds of methods (those that always succeed and those that can fail), checked exceptions would have worked out.
Some people extend RuntimeException instead, which means you don't know whether a generic RuntimeException is recoverable or not.
It's similar to how code formatting tools have been around a long time, but Go made their formatter standard, and that made all the difference. Conventions sometimes matter more than language features.
Conditionals are frustrating because they tend to be paired with indentation, which doesn’t "diff" well in a lot of tools and makes simple changes seem more extensive than they really are. In a sense, I shouldn’t have to re-indent half a function just because I happen to be changing the “preferred/happy path” that is buried inside several error checks.
On the other hand, early returns are frustrating because they enable lazy programmers to make quick hacks at the expense of complicating later maintenance (e.g. instead of having one “normal” path to consider, the next programmer has to find and understand all the short-cuts that someone has introduced throughout the code and make sure they will all work).
I suppose the most “compatible” change to existing languages would be something like a keyword or syntax to identify code that is only handling errors. That way, at least IDEs/editors/etc. could offer ways to intelligently hide code that apparently isn’t part of the normal flow of a function.
Fortunately languages are now more likely to have good mechanisms for declaring local blocks of reusable code (not banished to functions on far-away lines) so it is now more practical to write code in logical chunks that aren’t quite as indented. You can write a sequence of operations, maintain it without ugly "diffs", and still have indentation and error-checking, etc. at point of use.
I don’t really think it’s a good idea: Go’s lack of macros imply rather a lot of anonymous functions to get it to work, which would imply loads of parentheses & curly brackets. Not to mention that the lack of first-class type literals would make actually using it close to insane. But it’d certainly be interesting. It’d definitely not be idiomatic Go. Still … interesting.
How would you resume execution at the panic point?
A conditions system requires that you don't unwind, afaik Go's panic do in fact unwind.
You invert it: rather than panicking, then continuing from the panic point if things recover, you proceed, only panicking to perform a transfer of control. Interestingly, this is what Lisp does: SIGNAL[0] (the most primitive function) just looks for applicable handlers and calls them from most- to least-recent; this means that if a handler transfers control (panics, in Go terms) then the condition has been handled; if not, SIGNAL just returns NIL; ERROR[1] does the same thing, but calls INVOKE-DEBUGGER if no handler transfers control; CERROR[2] is like ERROR, but it adds a CONTINUE restart, which just lets control resume.
It’s possible to implement this same structure in Go: conditions.Signal() would search for applicable handlers and execute them in order; if control transfers then it’d never return; conditions.Error() would invoke one or more handlers, or the debugger, and would never return; conditions.ContinuableError() would invoke one or more handlers, or the debugger, but might return.
The key is that it’s possible to execute a restart in the dynamic context of the signalling function (via use of Go’s context.Context), and only rewind the stack when you don’t need to go back down it. I think — I’ve not yet implemented it!
0: http://www.lispworks.com/documentation/lw71/CLHS/Body/f_sign...
1: http://www.lispworks.com/documentation/lw71/CLHS/Body/f_erro...
2: http://www.lispworks.com/documentation/lw71/CLHS/Body/f_cerr...
The non-unwinding part is done by searching the chain of frames and calling functions, without taking any non-local control transfer.
The frame linkage is assisted by maintaining a global or thread-specific stack top variable. A frame is declared on the stack, then hooked into the list using the global variable. When a control transfer does take place, the value of that variable is properly maintained to discard the frames that are in functions being abandoned.
Source: been there, implemented that.
I'm not that familiar with go but from what I remember of the descriptions of panic/recover, something similar should be doable.
I see a waaaay big font on my monitor (3440x1440).
It's not valid for _everything_ so I don't agree with it entirely. But, some things that are exceptions in Java would make more sense as just returns because it is _valid_ output for a function.
I think it's the distinction between "the method can't perform what it's supposed to perform due to the input it received" vs "something unexpected happened and that's why the method couldn't perform what it was supposed to".
I'll try to give an example:
Imagine you have a method in Java for parsing a credit card, which follows a certain pattern for verifying CSV. If the pattern wasn't satisfied, you could have a:
Throw new IllegalArgumentException("Input does not match CSV string ([0-9])")
But to me _exception_ would signify something unexpected happened. Whereas here I'd like if I could just 'return' that the input was not correct, and therefore the method could not check the CSV.Whereas, for example, if you have a method that writes to a File and the file you provided does not have the right priviledge -> this is an Exception because the user could not expect this.
I'm having a hard time wording this as consisely as possible, I'm sorry if it seems a bit incomprehensive but I'll try to TL;DR:
Exceptions: Unexpected behaviour from system Error returns: Wrong input from user
If that makes sense :)
You're just trying to justify/rationalise that you like go's arbitrary positioning on the result/fault continuum (well not continuum, it's not really 1-dimensional), there are few positions which can't be justified there.
> But to me _exception_ would signify something unexpected happened.
Being provided random garbage when prompted for a CVV can reasonably be unexpected.
> Whereas, for example, if you have a method that writes to a File and the file you provided does not have the right priviledge -> this is an Exception because the user could not expect this.
Why would the user not expect ACL issues on something well known for involving ACLs?
Edit: where this breaks down in Java is trying to implement interfaces that don't declare the exceptions you're then forced to smuggle out.
Go is not perfect, no language is, and one of its biggest flaws is its odious error handling. And that is good, because nothing can be perfect.
Apropos of nothing, it's pretty amusing that the go faq entry criticizing exceptions has a typo.