Go defer, panic and recover
In Go, defer
, panic
, and recover
are keywords that are used for handling errors and cleanup operations.
defer
The `defer` statement is used to ensure that a function call is performed later in a program's execution, usually for purposes of cleanup. The deferred call is executed even if the function returns before the deferred call is reached. For example:func main() { defer fmt.Println("world") fmt.Println("hello") }
This program will print "hello" first, and then "world". The defer
statement delays the execution of fmt.Println("world")
until the end of the main()
function, ensuring that "world" is printed after "hello".
panic
The `panic` function is used to cause a runtime error and halt the program. When a panic occurs, the program will stop executing and print a stack trace of the error. For example:func main() { panic("something went horribly wrong") }
This program will panic with the error message "something went horribly wrong".
recover
The `recover` function is used to handle a `panic` and resume normal execution. `recover` can only be used inside a deferred function. If a `panic` occurs, `recover` stops the panic and returns the error value that was passed to the `panic` function. For example:func main() { defer func() { if err := recover(); err != nil { fmt.Println("Panic:", err) } }() panic("something went horribly wrong") }
This program will panic with the error message "something went horribly wrong", but the defer
statement will catch the panic and print the error message to the console. The recover
function returns the error message that was passed to the panic
function.
It's generally recommended to use panic
and recover
for handling exceptional situations, and to use error values for normal error handling.