美文网首页
golang err & panic 2022-07-25

golang err & panic 2022-07-25

作者: 9_SooHyun | 来源:发表于2022-07-25 21:42 被阅读0次

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

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

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

  • To the function F, when a function F calls panic, normal execution of F stops immediately. Any functions whose execution was deferred by F are run in the usual way, and then F returns to its caller

  • To the caller G, the invocation of F then behaves like a call to panic, terminating G's execution and running any deferred functions. This continues until all functions in the executing goroutine have stopped, in reverse order. At that point, the program is terminated with a non-zero exit code. This termination sequence is called panicking and can be controlled by the built-in function recover.

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的信息

相关文章

网友评论

      本文标题:golang err & panic 2022-07-25

      本文链接:https://www.haomeiwen.com/subject/qjbgirtx.html