Sobes.tech
Middle+

Mis on panic Go-s ja millal seda ei saa püüda?

sobes.tech AI

Vastus AI-lt

In Go, a panic is a mechanism used to handle critical errors during program execution. When the panic function is called, the current goroutine's execution is interrupted, and the stack unwinding process begins, during which deferred functions are called.

A panic can be recovered using the recover function, which must be called inside a deferred function. If recover is called outside of a deferred function, it cannot catch the panic.

However, there are situations where a panic cannot be recovered:

  • If the panic occurs in the main goroutine and is not recovered, the program will terminate unexpectedly.
  • If the panic occurs in system calls or in the runtime that do not allow recover.
  • If recover is called outside the context of a deferred function, it cannot prevent the program from terminating.

Example:

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered panic:", r)
        }
    }()
    panic("something went wrong")
}

In this example, the panic will be caught and handled, and the program will not terminate unexpectedly.