MDGSF Software Engineer

[GO] panic and recover

2017-11-10
GO

例子1

package main

import "fmt"

func main() {
    fmt.Println("main start")
    a()
    fmt.Println("main end")
}

func a() {
    fmt.Println("a start")
    defer func() {
        fmt.Println("c")
        if err := recover(); err != nil {
            fmt.Println(err) //这里的err其实就是panic传入的内容,55
        }
        fmt.Println("d")
    }()
    f()
    fmt.Println("a end")
}

func f() {
    fmt.Println("f start")
    panic(55)
    fmt.Println("f end")
}

输出:

main start
a start
f start
c
55
d
main end

例子2

package main

import (
    "fmt"
)

func main() {
    A()
    B()
    C()
}

func A() {
    fmt.Println("Func A")
}

func B() {
    defer func() {
        if err := recover(); err != nil {
            fmt.Println("Recover in B")
        }
    }()
    panic("Panic in B")
}

func C() {
    fmt.Println("Func C")
}

输出:

Func A
Recover in B
Func C

weixingongzhonghao

上一篇 [GO] defer

Comments

Content