How to keep count of go routines that are dead?

I have a piece of code where we run multiple go routines multiple to receive values. I am trying to keep count of how many go routines have died due to some exception or error. I don't want to update the count for normal execution.

  for {
    go func(){
       err := receiveValues()


Here, receiveValues will call other function and return err if they fail

func recieveValues() error{
  if err, val := callSomeFunc(); err != nil{
    return err

  if err2, val2 := callOtherFunc(val); err2 != nil{
    return err2

I could check when receiveValues() returns error and increment my count, but I also want to increment my count when go routine exits due to some panic or errors that I didn't expect, what will be the fool proof way to keep track to how many go routines have died?

1 answer

  • answered 2018-03-13 20:43 Grzegorz ┼╗ur

    Use deferred function that will recover from panic.

    func count() {
        err := recover()
        if err != nil {
            // count error
        } else {
            // count no error
    func trap() {
        defer count()
        if rand.Intn(2) >= 1 {
            panic("bad luck")