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
You are calling
mutex.Unlock()at the end in addition to thedefer mutex.Unlock(). So when the defer runs, it's already unlocked! Just delete: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.