Home  >  Article  >  Backend Development  >  How to catch errors in golang

How to catch errors in golang

(*-*)浩
(*-*)浩Original
2019-12-14 13:19:023409browse

How to catch errors in golang

func panic(interface{}) and func recover() interface{} are two functions used for error handling in Golang.

The function of panic is to throw an error message. From its parameter type, you can see that it can throw any type of error message. (Recommended learning: go)

If panic is called somewhere during the execution of the function, an error message will be thrown immediately, and the normal execution process of the function will terminate, but The defer statements defined before panic in this function will be executed in sequence. The goroutine stops executing immediately afterwards.

recover() is used to capture panic information.

recover must be defined in the defer statement before panic. In this case, when panic is triggered, the goroutine will not simply terminate, but will execute the defer statement defined before it.

Capture the panic error you set:

package main
import "fmt"
import "math"
func foo(a int) {
    defer fmt.Println("foo退出来了")
    defer func() {
        if r := recover(); r != nil {
            fmt.Printf("捕获到的错误:%s\n", r)
        }
    }()
    if a < 0 {
        panic("必须输入大于0的数")
    }
    fmt.Println("该数的方根为:", math.Sqrt(float64(a)))
}
func main() {
    var a int
    a = 10
    fmt.Printf("a=%d\n", a)
    foo(a)
    var b int
    b = -10
    fmt.Printf("b=%d\n", b)
    foo(b)
    fmt.Println("该goroutine还可以执行")
}
// ///////////
a=10
该数的方根为: 3.1622776601683795
foo退出来了
b=-10
捕获到的错误:必须输入大于0的数
foo退出来了
该goroutine还可以执行
Process finished with exit code 0

The above is the detailed content of How to catch errors in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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