recover
Although there is no try catch mechanism, Go actually has a similar recovery mechanism. The function is a bit weaker and the usage is very simple. Simple: (Recommended learning: go)
package main import "fmt" func main() { fmt.Printf("%d\n", cal(1, 2)) fmt.Printf("%d\n", cal(5, 2)) fmt.Printf("%d\n", cal(5, 0)) fmt.Printf("%d\n", cal(9, 2)) } func cal(a, b int) int { defer func() { if err := recover(); err != nil { fmt.Printf("%s\n", err) } }() return a / b }
First of all, everyone must understand the role of defer. Simply put, defer is similar to the destructor in object-oriented. In this function It will be executed when it terminates, even if it is terminated by panic.
So, every time the cal function terminates, it will check whether there is an exception. If it occurs, we can handle it, such as recording logs, so that the program can continue to execute.
package main import ( "errors" "fmt" "math" ) func main() { _, err := IntFromInt64(math.MaxInt32 + 1) if err != nil { fmt.Println(err) } } func ConvertInt64ToInt(i64 int64) int { if math.MinInt32 <= i64 && i64 <= math.MaxInt32 { return int(i64) } panic("can't convert int64 to int") } func IntFromInt64(i64 int64) (i int, err error) {//这里 defer func() { if err2 := recover(); err2 != nil { i = 0//这里 err = errors.New("ttt")//这里 } }() i = ConvertInt64ToInt(i64) return i, nil }
Main idea: Use defer to modify the value of the return variable (determined in advance as i and err) before return
The above is the detailed content of How to return after golang recover. For more information, please follow other related articles on the PHP Chinese website!