Go panic end process

func test_1 () {

exit:=make(chan struct{})
go func() {
    defer close(exit)
    defer println("exit")
    func(){
        defer func() {
            println("b:",recover()==nil,recover())
        }()
        func (){
            println("c")
            //runtime.Goexit()
            panic("panic done")
            println("c done")

        }()
        println("b done")
    }()
    println("a done")
}()
<-exit

}

clipboard.png

after calling panic, the subsequent process ends, and defer can continue to execute, but println ("a done") still outputs the result. In theory, why can you output "a done" if this part should not be output after panic call?

May.11,2021

uses recover to recover from panic, and the defer for recovering panic is nested in an internal anonymous function. You can think of this part as another function called. Defer will be executed after panic. Since panic is restored, it will not affect the output of a done.


clipboard.png

a done outside

Menu