golang err & panic 2022-07-25

2022-07-25  本文已影响0人  9_SooHyun

Java 中,Throwable 是所有错误(Error)和异常 (Exception) 的基类
Exception 是可预料的,而 Error 是不可预料的

Go 的异常错误设计体系只有 Error,任何一切都在方法返回值中返回可能发生的错误

The panic built-in function stops normal execution of the current goroutine. 一般来说,当程序继续运行不能得到正确结果,或者继续运行会导致系统崩溃等预期外的结果时,应当panic

simple panic demo:

// You can edit this code!
// Click here and start typing.
package main

import "fmt"

func main() {
    test()
}

func test() {
    defer fmt.Println("in test")
    defer func() {
        defer func() {
            panic("panic again and again")
        }()
        panic("panic again")
    }()

    panic("panic once")
}

// in test
// panic: panic once
//  panic: panic again
//  panic: panic again and again
// goroutine 1 [running]:
// main.test.func1.1()
// ....

simple panic and recover demo:

// You can edit this code!
// Click here and start typing.
package main

import "fmt"

func main() {
    // make recover here
    defer func() {
        if e := recover(); e != nil {
            fmt.Println("panic is: ", e)
        }
    }()

    test()
}

func test() {
    defer fmt.Println("in test")
    defer func() {
        defer func() {
            panic("panic again and again")
        }()
        panic("panic again")
    }()

    panic("panic once")
}

// in test
// panic is:  panic again and again
// 注意:recover只会handle最后一次panic的信息
上一篇 下一篇

猜你喜欢

热点阅读