News for hackers. Stuff that matters.
Re:On the uses and misuses of panics in Go by ilovecaching on Thursday August 09, 2018 @03:42PM (#17727760)
IMO Go's error handling is a flop. I constantly see code with the same verbose error checking that simply shoves the error further up the stack. No better than try/catch. Maybe and Either are much more elegant solutions that allow errors to be checked when values are needed rather than when they are created. I also really like monadic catch/throw.

Panic is an anti-pattern, I think, and seems oddly placed as I think the article was illustrating. Once again, these types of failures would be easier to represent with a richer type system.

Re:On the uses and misuses of panics in Go by munificent on Thursday August 09, 2018 @05:08PM (#17728522)
> I constantly see code with the same verbose error checking that simply shoves the error further up the stack.

I found this tragicomically illuminating:

https://anvaka.github.io/common-words/#?lang=go

The four most common words in Go programs are literally: "if", "err", "return", "nil". If that doesn't tell you the designers missed the boat on something, I don't know what does.

What I find frustrating is the attitude that went along with it. I think it's reasonable to say, "Yeah, error-handling is important but we think Java-style exceptions have too many problems. We don't want to do that, but we're not sure what a better alternative is yet. It's a hard problem."

But instead, it's: "Our proposal instead ties the handling to a function - a dying function - and thereby, deliberately, makes it harder to use. ... If you're already worrying about discriminating different kinds of panics, you've lost sight of the ball."

It's never the language being wrong, you're just using it wrong.

Good error-handling is hard. Users want to be forced to handle errors that they want to ensure are handled, but not annoyed by errors they don't care about. Telling which from which is highly contextual, and the language rarely has that knowledge.

Re:On the uses and misuses of panics in Go by dilap on Thursday August 09, 2018 @05:45PM (#17728815)
I don't know. I find the distinction of "panic if it's a bug, return err if it's a normal condition" to work pretty well.

It's much easier for me to write robust server software in Go than in either Java or Python -- because I don't constantly have to be thinking, "oh, is this thing going to suddenly unexpectedly throw?"

Basically, exceptions for exceptional conditions is good. But Java and Python use exceptions for normal conditions, which is cumbersome and annoying.

So for me, Go's approach to error handling is an improvement over just exceptions. The fact that it's verbose is fine if maybe not ideal.

(My vague understanding (just from reading, not using) is that's rusts is similar but more ergonomic. Ditto for Zig.)

Re:On the uses and misuses of panics in Go by atombender on Thursday August 09, 2018 @11:15PM (#17730433)
The problem in Go isn't that the semantics are wrong, it's that the error handling is so prevalent that it starts obscures your logic. I'm writing an app right now where almost every piece of high-level code is:

  if err := doThis(); err != nil {
    return err
  }
  if err := doThat(); err != nil {
    return err
  }
  if err := doThisOtherThing(); err != nil {
    return err
  }
  // ...
The patterns in Go code are typically either (1) "call this and bail if error" or (2) "call this and bail if error, wrapping the error in a new error", with a sprinkling of (3) "if the error is io.EOF or whatever, do something else".

The #1 case is so dominant that Go really cries out for a built-in error-propagation mechanism.

The other problem with Go's error handling is the use of multi-value return types. I suspect Go's designers thought this was elegant, but it confuses things, because all error-returning functions return either a value or an error. Never both. It's not two return values in actuality, it's a sum type (aka product type or union). I'd take this over the current scheme:

  func GetFile() (io.Reader | error) { ... }
And then maybe:

  switch t := GetFile().(type) {
    case io.Reader: ...
    case error: return err
  }
which can have the following semantic sugar:

  r := try GetFile()
Rust has a macro that does something like the above, but the type system supports sum types and matching already.

Now you can do:

  r := try GetFile()
  count := try r.Read(buf)
instead of:

  r, err := GetFile()
  if err != nil {
    return err
  }
  count, err := r.Read(buf)
  if err != nil {
    return err
  }
Re:On the uses and misuses of panics in Go by dilap on Friday August 10, 2018 @03:02AM (#17731249)
agreed; there's real (potential) niceness in these ideas.
Re:On the uses and misuses of panics in Go by nemothekid on Thursday August 09, 2018 @07:39PM (#17729505)
>The four most common words in Go programs are literally: "if", "err", "return", "nil". If that doesn't tell you the designers missed the boat on something, I don't know what does.

Are you trying to make a case for exceptions? If so, this isn't it. The "boat" the designers missed are Result types, or more generally "generics". I'm willing to bet most go function signatures are of f(...) (T, error). The if a,err := g(); err != nil boilerplate could be solved with Rust's `?` operator. For example:

    var exp int
    if a, err := compute(); err == nil {
        exp = a
    } else {
        return nil, err
    }
could be rewritten as

    exp := compute()?
Rust has `Result<T,E>` which makes this "simple". A `?` style operator in go would probably drastically reduce the mount of `err != nil` code in the wild.

At the same time, the code is still being shoved up the stack.

Re:On the uses and misuses of panics in Go by munificent on Friday August 10, 2018 @12:38PM (#17734807)
I'm not making a case for any specific language feature. I like exceptions, result types, and Icon's notion of failure. Just something that's better than what Go has today.
Re:On the uses and misuses of panics in Go by bGl2YW5j on Thursday August 09, 2018 @08:05PM (#17729640)
I too, have found error handling in Go to be quite good even if it is verbose. I like knowing where exactly an error has come from and that the language makes me think about how to handle them before continuing.

> ...but not annoyed by errors they don't care about. Telling which from which is highly contextual, and the language rarely has that knowledge.

Isn't this where the programmer's knowledge + a little thinking come into it? With experience you come to understand what kind of errors certain functions will return and then you spend a little time thinking about the context this error may appear. With this you determine whether the error has to be handled or can be safely ignored via a '_'.

Re:On the uses and misuses of panics in Go by orangecat on Friday August 10, 2018 @12:01AM (#17730591)
With this you determine whether the error has to be handled or can be safely ignored via a '_'.

In my experience most of the time I want to neither explicitly handle the error nor ignore it. I want it to propagate up to a top-level handler that logs it and either fails the current operation or aborts the entire program.

Re:On the uses and misuses of panics in Go by cpeterso on Thursday August 09, 2018 @05:53PM (#17728888)
The Icon programming language has a nice error handling style that reminds me of Go's local error handling but with less boilerplate. Functions can return success/failure along with the actual return value, like an implicit Maybe/Option type.

Converting the article's example code from Go:

  f, err := os.Open("file.txt")
  if err != nil {
    // handle error here
  }
to pseudo-Icon:

  if f := os.Open("file.txt") then
    read(f)
  else
    handle error here
https://en.wikipedia.org/wiki/Icon_(programming_language)
Re:On the uses and misuses of panics in Go by scns on Friday August 10, 2018 @03:48AM (#17731422)
iirc it works like that in swift:

if let file = os.Open(file) { do sth } else { handle error }

Re:On the uses and misuses of panics in Go by cdoxsey on Thursday August 09, 2018 @09:14PM (#17729945)
Practically the verbosity isn't a big deal. It's not hard to type and you can always copy and paste.

More importantly, as a pattern it's pretty easy to read. The code and meaning is clear and you can follow it.

Maybe some syntax would be nice to shorten it, but it really doesn't bother me all that much. You get used too it.

Bigger problems are language warts which lead to bugs, and a nasty one has to do with interfaces and nil: https://golang.org/doc/faq#nil_error . Seems like it would be much better for them to fix that. (and there are attempts to do so in issues on GitHub)

FWIW the errors package is a nice way to further annotate errors: https://github.com/pkg/errors

And at least with distributed systems error handling is a more complicated affair. The boilerplate ends up not being so boilerplate when some errors should be ignored, some retried and some should result in a panic.

I guess there's an appeal to a well defined exception type hierarchy for something like that, though how that fits with a language like go isn't at all clear... in practice knowing the type hierarchy is also hard ... what's the difference between Error and Exception ends up being a common bug in python for example.

We treat these problems like they have obvious solutions, but they don't. Fixing them the "easy" way ends up turning Go into a very different language, and it will be a sad day when that happens.

Folks who enjoy working with Go will just fork a minimalist version, and the folks who complained won't use it anyway and will stick with rust or whatever. At least that's my sense of it.

Re:On the uses and misuses of panics in Go by platinumrad on Thursday August 09, 2018 @04:22PM (#17728116)
I also prefer the option monad, etc. over returning (result, result..., err) tuples but terseness of error handling is as much a property of the language (i.e. operators, features, etc.) as it is a property of the type system. Consider the "try!/?" pseudo-macro from Rust. If Go had macros, there would be nothing preventing something similar from being implemented.
Re:On the uses and misuses of panics in Go by cesarb on Friday August 10, 2018 @06:29AM (#17732082)
> Consider the "try!/?" pseudo-macro from Rust.

On Rust, try! is not a pseudo-macro, it's an actual macro (which could be defined by anyone, since it uses only the public API for Result and From). Go to https://doc.rust-lang.org/std/macro.try.html and click on the [src] link at the top to see its current definition.

Re:On the uses and misuses of panics in Go by platinumrad on Friday August 10, 2018 @05:51PM (#17736988)
I called it a pseudo-macro because while "try!" is a macro, its usage is discouraged in favor of "?", which is an operator.
Re:On the uses and misuses of panics in Go by majewsky on Thursday August 09, 2018 @06:28PM (#17729101)
If Go had macros, it wouldn't have been as successful as it is. The appeal of Go is that it's both very readable and very writable, even if verbose.
Re:On the uses and misuses of panics in Go by bbatha on Thursday August 09, 2018 @09:03PM (#17729897)
Go already has code generation built into the standard tooling. It also has reflection which is arguably worse because the generated code is totally opaque. Good macros would cover most of the uses cases for the tools in a more cohesive and more tooling friendly way.
Re:On the uses and misuses of panics in Go by rmrfrmrf on Thursday August 09, 2018 @10:31PM (#17730267)
Isn't Go's error handling basically just a procedural version of Either? It's a tuple instead of a sum type and the Left and Right cases are flipped, but otherwise I thought the entire point was that you're dealing with values that you only need to worry about at access time.

Sure, it's not a proper functor, but for a procedurally-driven language design, I would think that the current design makes more sense for debugging.

Re:On the uses and misuses of panics in Go by atombender on Thursday August 09, 2018 @11:22PM (#17730470)
There's a major downside to the multi-value returns compared to sum types: They can't be chained. You have to assign the two result values to two separate variables:

  s, err := readFile()
There's no way to build something like this:

  readFile().then(func(s string) { ... })
Well, you can build it by having readFile() return some object with a then(), but without generics you can't build anything remotely ergonomic here.

(Actually, Go has an interesting quirk where multi-value return values can be passed as arguments to a function, so this is allowed:

  func handleErrors(s string, err error) { ...}
  func readFile() (string, error) { ... }
  func main() {
    handleErrors(readFile())
  }
Unfortunately, there's no way to build a generic chaining mechanism with this, since you'd have to have a handleErrors() for every possible return type combination.)
Re:On the uses and misuses of panics in Go by londons_explore on Thursday August 09, 2018 @04:22PM (#17728124)
You mean a bit like NaN in floating point math?

ie. code execution continues with the same flow, but any code that takes as input an error will return the same error.

Re:On the uses and misuses of panics in Go by iainmerrick on Thursday August 09, 2018 @09:03PM (#17729894)
I find NaN is mostly unhelpful on balance. It can help avoid crashes, but you get garbage results and it’s often hard to trace back to the underlying culprit. NaN means kicking the can down the road and failing as late as possible, but failing early means much easier debugging.

Something like a NaN (for arbitrary operations, not just floats) that could also give you a full backtrace would be very interesting -- a bit like Java’s nested exceptions.