📜  GO语言 defer

📅  最后修改于: 2021-01-02 09:09:43             🧑  作者: Mango

恐慌

恐慌是一种用于处理错误情况的机制。紧急情况可用于中止函数执行。当一个函数调用panic时,它的执行停止,控制流向相关的deferred函数。

此函数的调用方也将终止,并执行调用方的延迟函数(如果存在)。该过程一直持续到程序终止。现在报告错误情况。

此终止序列称为panicking,可以通过内置的函数restore控制。

恐慌示例1:

package main

import "os"

func main() {
    panic("Error Situation")
    _, err := os.Open("/tmp/file")
    if err != nil {
        panic(err)
    }
}

输出:

panic: Error Situation

goroutine 1 [running]:
main.main()
/Users/pro/GoglandProjects/Panic/panic example1.go:6 +0x39

恐慌示例2

package main

import "fmt"
func main() {
    fmt.Println("Calling x from main.")
    x()
    fmt.Println("Returned from x.")
}
func x() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in x", r)
        }
    }()
    fmt.Println("Executing x...")
    fmt.Println("Calling y.")
    y(0)
    fmt.Println("Returned normally from y.")
}

func y(i int) {
    fmt.Println("Executing y....")
    if i > 2 {
        fmt.Println("Panicking!")
        panic(fmt.Sprintf("%v" , i))
    }
    defer fmt.Println("Defer in y", i)
    fmt.Println("Printing in y", i)
    y(i + 1)
} 

输出:

Calling x from main.
Executing x...
Calling y.
Executing y....
Printing in y 0
Executing y....
Printing in y 1
Executing y....
Printing in y 2
Executing y....
Panicking!
Defer in y 2
Defer in y 1
Defer in y 0
Recovered in x 3
Returned from x.