Defer, Panic, and Recover in Go Explained

Defer schedules cleanup, panic halts execution for errors, and recover catches panics to restore normal flow.

Use defer to schedule cleanup code, panic to halt execution on unrecoverable errors, and recover to catch panics and resume normal flow. defer runs when the function returns, panic unwinds the stack, and recover stops the unwind inside a deferred function.

func safeDivide(a, b int) (int, error) {
	defer func() {
		if r := recover(); r != nil {
			// Handle panic here
		}
	}()
	if b == 0 {
		panic("division by zero")
	}
	return a / b, nil
}