A panic is designed to crash the application which is the default behaviour. However, if you want to prevent this from happening and let your application carry on running as if nothing has happened you will have to use recover function. The rule is, recover from panics only if you meant to. In short, don’t recover every panic by default. Instead, selectively recover by checking the panic type. Note: There is no recovery for conditions such as the application running out of memory.

Examples

Panic without recover

As shown below, the application crashed.

func main() {
	fmt.Println("main: begin")

	panic("Main function panicked!")

	fmt.Println("main: end")
}

// Output:
// main: begin
// panic: Main function panicked!
//
// goroutine 1 [running]:
// main.main()
// /Users/mysql/Server/Go/src/github.com/inanzzz/client/cmd/client/main.go:4 +0xb3
// exit status 2

#go

Recovering From Panic in Golang Applications
1.50 GEEK