>
> I realize that this thread ended up diverging into a wider discussion of
> exceptions and error handling in general but I wanted mention one of the
> problems I discovered and maybe a potential solution for others who may be
> tempted to play around with something like this.
>
> I originally thought that one of bigger problems with (ab)using panic and
> recover for control flow and trying to wrap this up in a package would be
> forgetting to defer the function performing the recover. As mentioned
> previously I think it's possible to structure things so that it is harder
> to make this mistake and I think a linter could also be written to catch
> these cases.
>
> But I think the bigger problem is the function that panics being used
> after the function with the deferred recover exits or in a different
> goroutine.
>
> It looks like the Go compiler's escape analysis can be used to detect this
> though. At least currently. With an inline definition of check and a
> deferred recover that looks like this:
>
> var check func(error)
> {
> pnc := false
>
> check = func(ce error) { // watch for "func literal escapes to
> heap"
> if ce != nil {
> err = ce
>
> // Only panic if we haven't previously.
> if !pnc {
> pnc = true
> panic("escaping")
> }
> }
> }
>
> defer func() {
> if pnc {
> _ = recover()
> }
> }()
> }
>
> // Code that uses check.
>
> When compiled with `go build -gcflags -m` if the Go compiler says that the
> func literal assigned to check escapes to the heap there's a good chance it
> is being used in a way that won't end well. It even catches uses like this:
>
> c := make(chan struct{})
>
> go func() {
> check(nil)
>
> close(c)
> }()
>
> <-c
>
> where check doesn't out live the function with the deferred recover but it
> is being used in a different goroutine. So, at least currently, it looks
> like the compiler can be used to check for unsafe uses of a function like
> this.
>
> What I'm wondering is are there cases that the compiler won't catch and is
> this likely to stop working in some future release where, in a block of
> code like the one above, the compiler will decide that the function doesn't
> need to escape to the heap?
>
> Michael.
>
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/d99b705e-d78a-4078-8f8a-ef89a824f58cn%40googlegroups.com.