I
I
impressive172020-07-20 23:00:06
go
impressive17, 2020-07-20 23:00:06

What is the value of r after the second panic call?

There is a code

package main

import "log"

func f() {
  defer func() {
    if r := recover(); r != nil {
      log.Printf("recover:%#v", r)
    }
  }()
  panic(1)
  panic(2)
}

func main() {
  f()
}

As I understand it, the first panic is processed correctly, while the second one is no longer processed, am I right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2020-07-20
@impressive17

The execution of the f() function ends after the first panic, then it executes defer.
The second panic will not be executed, because The execution of the function has already ended and the queue will not reach it.
You can add some log.Println to your example and follow the progress like this

package main

import "log"

func f() {
  defer func() {
    if r := recover(); r != nil {
      log.Printf("recover:%#v", r)
    }
  }()
  log.Println("Start first panic")
  panic(1)
  log.Println("After first panic")
  panic(2)
  log.Println("After second panic")
}

func main() {
  f()
  log.Println("After f()")
}

The output will be like this
2020/07/20 23:14:07 Start first panic
2020/07/20 23:14:07 recover:1
2020/07/20 23:14:07 After f()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question