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\n", p)
}
// how can I do?
}()
panic("test error")
return 10
}
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\n", p)
r = 5 // this modify the return value
}
}()
panic("test error")
return 3
}
func main() {
fmt.Println(foo()) // this print 5
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With