Detailed explanation of Golang panic usage

藏色散人
Release: 2020-09-28 13:20:15
forward
2549 people have browsed it

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

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!

Related labels:
source:cnblogs.com
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