News for hackers. Stuff that matters.
Re:Toward Go 1.3 by tptacek on Tuesday February 11, 2014 @12:42PM (#7218915)
I don't think they're "figuring out" exceptions; my understanding is, they're not going to happen.

I am also not a fan of hyperliteral case-by-case error checking (it reminds me of my early C code), but it's A Style, one that the Golang team enthusiastically adopts, and it's unlikely to go anywhere.

Re:Toward Go 1.3 by voidlogic on Tuesday February 11, 2014 @01:03PM (#7219068)
Go's returned error allows very varied error handling if wanted/needed: http://play.golang.org/p/-2q6N08x_P

More than just the normally used: if err := foo(); err != nil; { return err }

Large code Go code basis are so much better (more maintainable) for "hyperliteral case-by-case error checking". My impression that only people who havn't written large Go projects have this complaint.

Also, there is no reason you could not define a function like:

  func foobar() (fatalErr, err error)
Re:Toward Go 1.3 by bad_user on Tuesday February 11, 2014 @05:05PM (#7220826)
That seems to me like an awful example. But speaking of generics, exceptions and other things that Go lacks, like pattern matching, lazy values, currying and so on, in my opinion Go sucks because you can't abstract well over common patterns. To take your example as a use-case:

    object NonFatalError {
      def unapply(err: Throwable) = err match {
        case _: TimeoutException => Some(err)
        case _: IOException => Some(err)
        case _ => None
      }
    }

    def executeWithRetries[T](maxTries: Int)(callback: => T): T = 
      try {
        callback
      } 
      catch {
        case NonFatalError(error) if maxTries > 0 =>
          logger.warn(error)
          executeWithRetries(maxTries - 1)(callback)
        case other: Throwable =>
          throw other
      }
And usage:

    def funcMayErr(): Int = throw new TimeoutException

    val value = executeWithRetries(5) {
      funcMayErr()
    }
But there's more. Because with generics and exceptions you can actually wrap the whole result in an algebraic data-type that also has handy methods for dealing with failure (e.g. a monad), as in:

    Try(executeWithRetries(5)(funcMayErr)).map(x => x + 1).getOrElse(default)
Cheers,
Re:Toward Go 1.3 by ithkuil on Wednesday February 12, 2014 @05:06AM (#7223465)
There are 3 kinds of people that read code:

* those casually glancing over to figure what the code does * those actually trying to figure out what a given expression does, either because they are reviewing or debugging * compilers are people too

Conciseness is often overvalued and pursued to the extreme where effort is made first by the author to seek for the perfect oneliner, and then for the reader to actually check that this code is doing what expected.

Composition is important, but I don't think I found great real world examples of composition which wasn't either working only because of a tightly controlled code base or because it was just an example to prove a point.

Don't get me wrong, I love scala/haskell, I find playing with those constructs interesting and beautiful.

It's just that Go is a different thing, is a modern approach of getting back to basics, a minimal toolset for do just programming, more or less translation of thought into instructions.

And it's works very well; it's very easy to get things done quickly and the produced code tends to be easily maintainable. It's easy to have control over the memory footprint. The tooling is very mature (http://blog.golang.org/race-detector, gofmt formatting+refactoring)

Re:Toward Go 1.3 by reyan on Tuesday February 11, 2014 @06:11PM (#7221238)
I think many of us want Go to be something it doesn't want to and will never be. There is potential for a fast, simple, statically typed language; borrowing good ideas from Lisp, ML and others (and NOT resulting in something like Scala).
Re:Toward Go 1.3 by enneff on Tuesday February 11, 2014 @05:47PM (#7221089)
You just don't know Go if you think it "can't abstract well over common patterns".
Re:Toward Go 1.3 by coldtea on Tuesday February 11, 2014 @11:49PM (#7222565)
Well it can't. Take for example "sort", "map", "filter" etc.

That it can abstract some other "common patterns" doesn't solve this.

Re:Toward Go 1.3 by voidlogic on Tuesday February 11, 2014 @06:01PM (#7221176)
func execWithRetries(f func() error, retryc int) error

can easily be implemented in Go: http://play.golang.org/p/kMNqfY7LYX

Re:Toward Go 1.3 by tptacek on Tuesday February 11, 2014 @01:04PM (#7219076)
I'm not sure how that code example demonstrates something other than error checking that has to be written case by case at the call site of any function that might return an error.
Re:Toward Go 1.3 by voidlogic on Tuesday February 11, 2014 @01:11PM (#7219152)
Well it does demonstrate that, and I think that is a good attribute of Go. (And if the caller returned the error, it could be handled by a previous caller too btw)

What I was showing was that:

  try {
   foo()
  } catch (ex1 ExType1) {
   ...
  } catch (ex2 ExType2) {
   ...
  } catch (ex ExBaseType) {
   ...
  }
Type logic is completely possible, which while apparent to you is lost on some people who haven't work with non exception langs before.
Re:Toward Go 1.3 by jamwt on Tuesday February 11, 2014 @04:43PM (#7220685)
Not if you want to parameterize the exceptions. This kind of "matching" requires that you compare your exception "types" by exception "values", so you cannot provide parameterized information about what exactly failed.... which key? Which URL?

Underpowered error handling (and I'm not advocating for exceptions, persay), lack of generics (and the resultant copypasta party and interface{} runtime casting [aka, the return of void *]) are real warts in an otherwise fine language.

And I'm not just theorizing: I spend my days writing a large, nontrivial system in go.

I've used Haskell a lot before, and I'm not asking for no nulls or real ADTs (though I wouldn't complain), but generics + better typed errors would really help clean things up.

Meanwhile, a lot of us are just waiting for rust...

Re:Toward Go 1.3 by beatgammit on Tuesday February 11, 2014 @05:40PM (#7221036)
Maybe I'm missing something, but you can do this with a type switch: http://play.golang.org/p/jF_bPQdwxk

It just depends on what you're trying to accomplish, but most use-cases can be accomplished without exceptions. The other use-cases often indicate bad design.

As for generics, you can get 90% of the way there with interfaces. The use of `interface{}`--while sometimes necessary--is often an indicator of bad design.

In large code bases, you often don't need (or care) to know what underlying type something is. For example, you shouldn't care whether an `io.Reader` is a TCP socket, file or completely in-memory ala `io.Pipe()`.

There are times when type assertions are the best/only way to get something done, and that's why they're there, but those cases should be relatively infrequent.

Generics would make some things easier (Rust's implementation is quite nice), but it's not significantly impacting my productivity, and I certainly wouldn't consider switching languages just because Go lacks them.

EDIT: Added info about generics

Re:Toward Go 1.3 by azernik on Tuesday February 11, 2014 @08:06PM (#7221811)
Errors in Go are custom types; your error can be defined as, for example:

    type URLError {
        url String
    }

    func (e URLError) Error() String {
        return fmt.Sprintf("Invalid URL: %s", e.url)
    }
At which point a caller that wants to handle this error can either extract the URL to do fun things with it or just dump the Error() string.
Re:Toward Go 1.3 by 4ad on Wednesday February 12, 2014 @01:42AM (#7222935)
Of course you can, error is an interface, any number of concrete types can satisfy it, and you can use type assertions or type switches to unbox (and use) that concrete type.

This is a widely used idiom in Go.

Re:Toward Go 1.3 by justinsb on Tuesday February 11, 2014 @12:44PM (#7218934)
Exceptions are already in the language: panic/recover. Though discouraged, you can't assume they won't happen. To me, this seems like the "worst of both worlds". It doesn't feel like a final position to me, it feels like a 1.0 position.
Re:Toward Go 1.3 by mratzloff on Tuesday February 11, 2014 @12:54PM (#7219002)
But panics are not exceptions. They should not be used like exceptions, and there is no "hierarchy of panic types".

They are used for things like out of bounds indexes, where in C it would simply be a segfault. A panic is a way of gracefully exiting a program that would have segfaulted otherwise. Correct code should check for out of bound indexes either way.

Re:Toward Go 1.3 by georgemcbay on Tuesday February 11, 2014 @02:04PM (#7219604)
I agree, but would also point out that panic isn't necessarily going to exit a program, recover exists and it isn't that uncommon for programs or libraries to do a deferred recover at the beginning of goroutines so that a panic within that goroutine will only kill off that goroutine and allow the main goroutine and other goroutines to continue.

Of course this "pattern" should only be used when you're sure that that one failing goroutine won't have a cascading impact on other goroutines that are still running.

Re:Toward Go 1.3 by pcwalton on Tuesday February 11, 2014 @01:06PM (#7219097)
Not all exception systems have type hierarchies. Neither ML nor Haskell have inheritance and both have exceptions.
Re:Toward Go 1.3 by ben0x539 on Tuesday February 11, 2014 @08:10PM (#7221830)
Haskell exceptions form a hierachy though.
Re:Toward Go 1.3 by justinsb on Tuesday February 11, 2014 @01:04PM (#7219074)
I think I've answered this elsewhere: the issue for me is that you have to handle exceptions _and_ error codes.

Though you raise an interesting point: Should you check array indexes if the runtime is also checking it for you?

In Java, the runtime is guaranteed to throw an exception and it is relatively rare that you would pre-check the array indexes (you might use assertions in debug code).

Incidentally, array bounds checking is actually relatively expensive, to the point where most JVMs (which use signed indexes) use an unsigned comparison trick to make it one comparison instead of two. So it does matter...

Re:Toward Go 1.3 by redbad on Tuesday February 11, 2014 @03:27PM (#7220174)
If you're recovering from panics, in general, you're doing something wrong.
Re:Toward Go 1.3 by enneff on Tuesday February 11, 2014 @05:48PM (#7221099)
> the issue for me is that you have to handle exceptions _and_ error codes.

Except you don't. I haven't used recover in any of my code for a long time (more than a year). Most of the time you don't need to worry about handling panics, but you can if you really need to.

> Should you check array indexes if the runtime is also checking it for you?

In Go the generated code does it. You shouldn't do it yourself.

Re:Toward Go 1.3 by justinsb on Tuesday February 11, 2014 @08:36PM (#7221911)
I consider defer to be part of handling exceptions, but I can see how we differ here.

We're seriously drifting off track here, but if we should rely on Go to check array indexes, that seems like you _would_ want a recover block, so that we can map it to a Go-preferred error code?

Re:Toward Go 1.3 by enneff on Tuesday February 11, 2014 @08:57PM (#7221990)
Go doesn't have exceptions. Can you please stop saying it does? There's a reason we didn't give "panic" the name "throw". Because they work differently and are used for different things.

There's also no such thing as a "recover block" (you're thinking of a "finally block" or "catch block", neither of which exist in Go).

If we thought you should use recover any time there might be an array out of bounds panic, we'd have designed the whole language differently. Panics should happen when things go badly wrong, and most of the time that means your program should crash.

You should use recover only in two rare cases: 1. where you're specifically using panic/recover as a kind of setjmp/longjmp (as it is used within encoding/json, for example), and 2. where you don't want a programming error to bring down your entire program, such as in the base net/http handler (although I think it's debatable whether we should have done it there; but it's done now and we can't change it).

It amazes me that there has been so much discussion over this incredibly minor and seldom-used feature. Just return and check errors (and just panic when things go really wrong) and get on with your life.

Re:Toward Go 1.3 by collinvandyck76 on Tuesday February 11, 2014 @07:02PM (#7221550)
Doesn't the http package's Server recover from panics in the goroutines that are created to serve requests? That bugged me when I saw it happen. If my request handler panics, I wouldn't expect the server to recover from it.
Re:Toward Go 1.3 by tptacek on Tuesday February 11, 2014 @12:46PM (#7218942)
You can abuse "panic" to implement exceptions in Golang the way you can abuse "longjmp" to do that in C. The purpose of "panic" isn't for general-purpose exceptions. It's to panic the program.
Re:Toward Go 1.3 by mjibson on Tuesday February 11, 2014 @03:27PM (#7220171)
Note that this mechanic is used in the golang standard library and works great as a catchall: http://golang.org/src/pkg/text/template/exec.go#L93
Re:Toward Go 1.3 by justinsb on Tuesday February 11, 2014 @12:50PM (#7218975)
It's clear you shouldn't throw.

But correct code must assume that any function you call might throw; which is why you should use defer blocks e.g. to release resources, instead of C-style "cleanup at the bottom of the function". (Defer is also prettier IMHO)

Re:Toward Go 1.3 by JulianMorrison on Tuesday February 11, 2014 @04:40PM (#7220651)
It's idiomatically correct to ignore panics and let them take the whole program down with a crash. A panic indicates that your program is already doing extremely incorrect things. Rare is the program where picking itself up and continuing a possible Sorcerer's Apprentice mode rampage is better than just stopping and telling you what needs fixing.
Re:Toward Go 1.3 by tptacek on Tuesday February 11, 2014 @01:59PM (#7219563)
You're not "throwing". You're "panicking".
Re:Toward Go 1.3 by ithkuil on Wednesday February 12, 2014 @03:02AM (#7223137)
Or raising? That's just terminology. The behaviors of c++/java/python exceptions and Go panics are similar regardless of the name the keyword has in those language:

The execution is suspended, the stack unwound until the first handler, the handler has access to a value that is "thrown". Stack information is preserved in order to print meaningful stack traces.

C++/java/python have syntax sugar that performs a pattern match on the thrown object to decide whether to handle it or bubble it up, while in Go you do it manually, but other that that I don't see much of a difference in the mechanics of them to justify being so pedantic about the naming of the action.

Re:Toward Go 1.3 by joncooper on Tuesday February 11, 2014 @01:04PM (#7219078)
The point is that an exception in Go world means: something which should not ever happen, and which renders continued execution impossible. IMO recover should only be used to wind down execution in as graceful a manner a possible prior to terminating the program.

As opposed to an error, which can and will happen.

Re:Toward Go 1.3 by aaronblohowiak on Tuesday February 11, 2014 @05:50PM (#7221107)
we should rename recover to "log this before terminating the process"