Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Defer, Panic and Recover

15. Defer, Panic, and Recover

Defer, Panic, and Recover are three mechanisms in Go that allow you to handle exceptional situations and control the flow of your programs. Let's explore these concepts in detail, along with examples.

Defer in Go:

The 'defer' statement is used to schedule a function call to be executed just before the surrounding function returns. Deferred functions are executed in reverse order, i.e., the last deferred function is executed first.

Example of Defer:
func main() {
defer fmt.Println("This will be printed last.")
fmt.Println("This will be printed first.")
}

 

In this example, "This will be printed first." is printed before "This will be printed last.", even though the 'defer' statement appears later.

Panic in Go:

The 'panic' function is used to cause a program to panic, which means it terminates abruptly. A panic is typically used when something unexpected happens, like an unrecoverable error.

Example of Panic:
func main() {
fmt.Println("Start of main")
panic("Something went wrong!") // This will cause a panic
fmt.Println("End of main") // This line won't be executed
}

 

In this example, the program panics after the "Start of main" is printed. The line "End of main" is not executed.

Recover in Go:

The 'recover' function is used to catch a panic and allow the program to recover from it. It's typically used in deferred functions to prevent a panic from causing the whole program to crash.

Example of Recover:
func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered:", r)
        }
    }()
    panic("Something went wrong!")    // This will be caught by recover
}

 

In this example, the 'recover'  function is used to catch the panic caused by the 'panic' statement. The deferred function prints "Recovered: Something went wrong!" before the program exits.

Combining Defer, Panic, and Recover:

Combining these mechanisms can be powerful for handling errors gracefully.

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

fmt.Println("Start of main")
panic("Something went wrong!") // This will be caught by recover
fmt.Println("End of main") // This line won't be executed
}

 

In this example, the deferred function with the 'recover' call catches the panic, allowing the program to print "Recovered: Something went wrong!" instead of crashing.

Summary:

  • 'defer' schedules a function to be executed just before a function returns.
  • 'panic' is used to cause a program to panic and terminate abruptly.
  • 'recover' is used to catch a panic and allow the program to recover from it.
  • Combining 'defer', 'panic', and 'recover' can help handle unexpected situations gracefully.

Understanding 'defer', 'panic', and 'recover' allows you to handle exceptional situations in your Go programs. While it's recommended to avoid using panics in favor of structured error handling, these mechanisms provide ways to manage unexpected scenarios when necessary.