Recover
Go provides us with the ability to regain control after a panic has occurred. recover()
is a function that is used to regain control of a panicking goroutine.
The signature of the recover()
function is as follows:
func recover() interface{}
The recover()
function accepts no arguments and returns an empty interface{}
. For now, an empty interface{}
indicates that any type can be returned. The recover()
function will return the value sent to the panic()
function.
The recover()
function is only useful inside a deferred function. As you may recall, a deferred function gets executed before the encompassing function terminates. Executing a call to the recover()
function inside a deferred function stops the panicking by restoring normal execution. If the recover()
function is called outside a deferred function, it will not stop the panicking.
The following diagram shows the steps a program would take when using panic()
, recover()
, and a defer()
function: