Sobes.tech
Junior — Middle

In what cases is it necessary to catch and handle panic errors in a program?

sobes.tech AI

Answer from AI

Handling panic errors (panic) is necessary in cases where it is important to guarantee the correct termination of the program or recovery after critical errors to avoid crashes.

For example:

  • In server applications, to prevent the entire service from crashing due to one error.
  • When working with external resources, to properly close files, connections.
  • In libraries, to give users the opportunity to handle critical errors.

This is done using recover() inside a deferred function (defer), which catches the panic and allows the program to continue working or terminate correctly.

Example:

func safeFunction() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Panic caught:", r)
        }
    }()

    // Code that may cause panic
    panic("something went wrong")
}