Defer, Panic, and Recover in Go
Go provides three statements that can be used to manage program execution in the presence of errors: defer, panic, and recover.
The defer statement is used to schedule a function call to be executed after the current function completes, whether it completes normally or due to an error:
func main() {
defer fmt.Println("done")
fmt.Println("hello")
}
In this example, we use the defer statement to schedule a call to fmt.Println("done") after the main function completes. The defer statement is useful for releasing resources, such as closing files or network connections, after a function completes.
The panic statement is used to indicate that an unexpected error has occurred, and the program cannot continue:
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered from panic:", r)
}
}()
panic("something bad happened")
fmt.Println("this line will not be executed")
}
In this example, we use the panic statement to indicate that an error has occurred. We also use the recover statement to catch the panic and handle it gracefully. When a panic occurs, the program execution stops immediately, and the deferred functions are executed before the program exits.
The recover statement is used to catch a panic and handle it gracefully:
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered from panic:", r)
}
}()
panic("something bad happened")
fmt.Println("this line will not be executed")
}
In this example, we use the recover statement to catch the panic and handle it gracefully. When a panic occurs, the program execution stops immediately, and the deferred functions are executed before the program exits.
No comments:
Post a Comment