This section will present you with a tricky technique that was first mentioned in Chapter 1, Go and the Operating System. This technique involves the use of the panic()
and recover()
functions, and it will be presented in panicRecover.go
, which you will review in three parts.
Strictly speaking, panic()
is a built-in Go function that terminates the current flow of a Go program and starts panicking! On the other hand, the recover()
function, which is also a built-in Go function, allows you to take back the control of a goroutine that just panicked using panic()
.
The first part of the program follows:
package main import ( "fmt" ) func a() { fmt.Println("Inside a()") defer func() { if c := recover(); c != nil { fmt.Println("Recover inside a()!") } }() fmt.Println("About to call b()") b() fmt.Println("b() exited!") fmt.Println("Exiting a()") }
Apart from the import
block, this part includes the implementation of the a(...