Sobes.tech
Junior — Middle

Kas on võimalik püüda ja töödelda panikaid defer-kutsumise sees Go-s?

sobes.tech AI

Vastus AI-lt

In Go, you can use defer to handle panics, but the call to defer itself does not catch a panic; you need to catch the panic inside the deferred function using recover().

Example:

func safeCall() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Panic caught and handled:", r)
        }
    }()
    panic("something went wrong")
}

Here, recover() is called inside the deferred function and allows catching the panic that occurs in safeCall. Thus, panics cannot be "caught" directly in defer, but they can be handled inside the deferred function with recover().