Failed to Recover from Panic during mutex lock and unlock

128 Views Asked by At

I am trying to check if i can recover panic from this code:
I have deliberately added mutex.Unlock() at line x

func main() {
   defer panicHandler()
   x := []int{1, 2, 3, 4}
   var mutex sync.Mutex
   mutex.Lock()
   defer mutex.Unlock()
   fmt.Println(x[2])
   mutex.Unlock()    // line x
}

func panicHandler() {
   rec := recover()
   if rec != nil {
       fmt.Println("Panic occurred - ", rec)
   }
}

It is giving - fatal error: sync: unlock of unlocked mutex

Moreover the flow didnt go inside panicHandler. Can anyone help me to understand this

I was expecting control flow to go inside the panicHandler() method and get recovered but it didnt happen this

1

There are 1 best solutions below

2
Andrew Arrow On

You are calling mutex.Unlock() at the end in addition to the defer mutex.Unlock(). So when the defer runs, it's already unlocked! Just delete:

mutex.Unlock()    // line x

It didn't goto panic because that's for runtime errors like accessing something that's nil. This is a FATAL error and you can't recover from that.