Home > Backend Development > Golang > How to return after golang recover

How to return after golang recover

(*-*)浩
Release: 2019-12-17 10:43:17
Original
4544 people have browsed it

How to return after golang recover

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
}
Copy after login

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&#39;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
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template