This question already has an answer here:
I have a problem how to modify return value with panic and recover in golang please help me, thank you!
func foo1() int {
defer func() {
if p := recover(); p != nil {
fmt.Printf("internal error: %v
", p)
}
// how can I do?
}()
panic("test error")
return 10
}
</div>
one way to do it is naming the return value in the func definition
package main
import "fmt"
func foo() (r int) {
defer func() {
if p := recover(); p != nil {
fmt.Printf("internal error: %v
", p)
r = 5 // this modify the return value
}
}()
panic("test error")
return 3
}
func main() {
fmt.Println(foo()) // this print 5
}