What is the difference between Go's panic and recover functions for handling runtime errors?

In Go, panic and recover are two built-in functions used for handling runtime errors. The panic function is used to indicate that a runtime error has occurred and the program cannot continue to run. On the other hand, the recover function is used to recover from a panic and continue execution.

When a **panic** is called, the program immediately stops executing the current function and begins to unwind the stack, executing deferred functions along the way until it reaches the top of the stack. If a deferred function calls **recover**, the **panic** is effectively canceled and the function returns normally. If no deferred function calls **recover**, the program terminates and prints a stack trace.

Here is an example of using **panic** and **recover**:

func example() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
    fmt.Println("Starting example")
    panic("something went wrong")
    fmt.Println("Ending example")

In this example, the **defer** statement sets up a function to be called when the current function returns. The **recover** function is called inside the deferred function, which checks if a panic occurred and, if so, prints the message "Recovered from panic:" and the value passed to **panic**.

When this function is called, it first prints "Starting example", then calls **panic** with the message "something went wrong". This causes the program to unwind the stack and call the deferred function, which calls **recover** and prints the message "Recovered from panic: something went wrong". The program then exits normally.

In summary, **panic** is used to signal a runtime error and **recover** is used to recover from a panic and continue execution. They can be used together to gracefully handle unexpected runtime errors.

Related Questions You Might Be Interested