Home  >  Article  >  Backend Development  >  Detailed explanation of Golang panic usage

Detailed explanation of Golang panic usage

藏色散人
藏色散人forward
2020-09-28 13:20:032547browse

The following column golang tutorial will introduce you to the detailed explanation of the usage of Golang panic. I hope it will be helpful to friends in need!

Detailed explanation of Golang panic usage

Go language pursues simplicity and elegance, so Go language does not support the traditional try...catch...finally exception, because the designers of Go language We believe that mixing exceptions with control structures can easily clutter the code.

Because developers can easily abuse exceptions, throwing an exception even for a small mistake. In Go language, multiple values ​​are used to return errors. Don't use exceptions to replace errors, let alone control the process. In rare cases, that is, when a real exception is encountered (such as the divisor is 0). Only use the Exception handling introduced in Go: defer, panic, recover.

The usage scenarios of these exceptions can be described simply: Go can throw a panic exception, then capture the exception through recover in defer, and then handle it normally.

package main

import "fmt"func main(){

    defer func(){ // 必须要先声明defer,否则不能捕获到panic异常
        fmt.Println("c")        if err:=recover();err!=nil{
            fmt.Println(err) // 这里的err其实就是panic传入的内容,55        }
        fmt.Println("d")
    }()

    f()
}

func f(){
    fmt.Println("a")
    panic(55)
    fmt.Println("b")
    fmt.Println("f")
}


输出结果:

a
c
d
exit code 0, process exited normally.

The above is the detailed content of Detailed explanation of Golang panic usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete