Recover

This lesson is a guide for programmers to recover their code from panic or any error condition.

We'll cover the following

What is recover() function?

As the name indicates, this built-in function can be used to recover from a panic or an error-condition: it allows a program to regain control of a panicking Go routine, stopping the terminating sequence and resuming normal execution. The recover is only useful when called inside a deferred function: it then retrieves the error value passed through the call to panic. When used in normal execution, a call to recover will return nil and have no other effect. The panic causes the stack to unwind until a deferred recover() is found or the program terminates.

Explanation

The protect function in the example below invokes the function argument g and protects callers from run-time panics raised by g, showing the message x of the panic:

func protect(g func()) {
  defer func() {
    log.Println("done") // Println executes normally even if there is a panic
    if err := recover(); err != nil {
      log.Printf("run time panic: %v", err)
    }
  }()
  log.Println("start")
  g() // possible runtime-error
}

It is analogous to the catch block in the Java and .NET languages. The log implements a simple logging package. The default logger writes to standard error and prints the date and time of each logged message. Apart from the Println and Printf functions, the Fatal functions call os.Exit(1) after writing the log message; Exit functions identically. The Panic functions call panic after writing the log message; use this when a critical condition occurs and the program must be stopped, like in the case when a web server could not be started.

The log package also defines an interface type Logger with the same methods when you want to define a customized logging system. Here is a complete example which illustrates how panic, defer and recover work together:

Get hands-on with 1400+ tech skills courses.