Junior — Middle
Is it possible to catch and handle panics inside a defer call in Go?
sobes.tech AI
Answer from AI
In Go, you can use defer to handle panics, but the call to defer itself does not catch panics — you need to catch the panic inside the function deferred with defer, 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 function deferred with defer, allowing it to catch a panic that occurs in safeCall. Thus, panics cannot be "caught" directly in defer, but they can be handled inside the deferred function with recover().