Is it possible to panic within a snooze function, especially when it has already panicked?

func sub(){
    defer func (){
        panic(2)
    }()
    panic(1)
}

func main(){
    defer func(){
        x:=recover()
        println(x.(int));
    }()
    sub()
}

I tried this code and it seems that the first panic is panic(1)just “overwritten” by the second panic panic(2).

But is everything alright? Or call the Golang function, which might panic inside the snooze function?

(In C ++, it is almost impossible to accept an exception from the destructor. It terminates the program if the stack is already disabled. I wonder if panic in this manner could be bad in the Golang.)

+4
source share
1 answer

Yes, everything is in order. Panic from a deferred function is not really a new, special state, it just means that the panic sequence will not stop.

, , panic(), , " msgstr" recover().

Spec: :

, G D, recover, goroutine, G. D, D recover , . D , , . , G , , .

, panic() , . , panic() recover() "" , "" ( , recover() , panic() call).

. :

func main() {
    defer func() {
        fmt.Println("Checkpoint 1")
        panic(1)
    }()
    defer func() {
        fmt.Println("Checkpoint 2")
        panic(2)
    }()
    panic(999)
}

( Go Playground):

Checkpoint 2
Checkpoint 1
panic: 999
    panic: 2
    panic: 1

goroutine 1 [running]:
panic(0xfed00, 0x1040e140)
    /usr/local/go/src/runtime/panic.go:500 +0x720
main.main.func1()
    /tmp/sandbox284410661/main.go:8 +0x120
panic(0xfed00, 0x1040e0fc)
    /usr/local/go/src/runtime/panic.go:458 +0x8a0
main.main.func2()
    /tmp/sandbox284410661/main.go:12 +0x120
panic(0xfed00, 0x1040e0f8)
    /usr/local/go/src/runtime/panic.go:458 +0x8a0
main.main()
    /tmp/sandbox284410661/main.go:14 +0xc0

, panic(), , , panic().

recover() , "" :

defer func() {
    recover()
    fmt.Println("Checkpoint 1")
    panic(1)
}()
defer func() {
    recover()
    fmt.Println("Checkpoint 2")
    panic(2)
}()

( Go Playground):

Checkpoint 2
Checkpoint 1
panic: 999 [recovered]
    panic: 2 [recovered]
    panic: 1
...
+5

Source: https://habr.com/ru/post/1663726/


All Articles