refer: https://go101.org/quizzes/panic-recover-1.html
package main
import "fmt"
func ExamplePanicGo101_1() {
defer func() {
fmt.Print(recover()) // catch panic(1)
}()
defer func() {
defer fmt.Print(recover()) // catch panic(2)
defer panic(1)
recover() // no-op - B, should be called inside deferred function,
}()
defer recover() // no-op - A, should be called inside deferred function,
panic(2)
// Output:
// 21
}
The test passes.
Questions:
- I can understand
no-op - Ais no-op, since it's not called inside deferred function, but howno-op - Bis no-op? Since it's called inside deferred function, I though it should catch thepanic(2), but not.
I think you may have missed the following point re
defer:So when executing
the steps are:
recover()and, effectively,defer fmt.Print(2)(becauserecover()evaluates to2).defer panic(1)recover()- noop as there is no active panicpanic(1)fmt.Print(2)(remember that "Any functions deferred by F are then executed as usual")The following example may help: