Welcome to your guide on Go panic and recover! This tutorial is designed to help both beginners and intermediate learners understand how Go handles errors and how to handle them effectively using panics and recoveries.
In Go, panics and recoveries are mechanisms for handling runtime errors. When an unexpected error occurs, a panic is triggered. A recovery can then be used to handle the panic and resume the program.
A panic is a Go function that indicates a severe error, causing the current Goroutine to terminate. It's like shouting "STOP!" when something goes wrong.
func examplePanic() {
panic("An error occurred")
}In the above example, examplePanic function will trigger a panic with the message "An error occurred".
A recover function is used to resume the execution of a program after a panic has occurred. It returns the value passed to the panic or nil if no panic has occurred.
func exampleRecover() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
examplePanic()
}In the above example, exampleRecover function uses a deferred function to recover from a panic. The recover function inside the deferred function will catch the panic and print the recovered value.
Panics and recoveries are useful when dealing with unexpected errors that can't be handled using regular error types. They provide a way to handle critical errors that could cause the program to crash if not handled.
Go has two types of panics:
Built-in panics: These are predefined panics that are triggered by specific conditions, like dividing by zero or accessing a nil slice element.
User-defined panics: These are custom panics that you can create and trigger as needed.
Here's an example of handling a user-defined panic and a built-in panic:
package main
import (
"fmt"
"math"
)
func exampleUserDefinedPanic() {
if false {
panic("User-defined panic")
}
}
func exampleBuiltinPanic() {
fmt.Println(math.Sqrt(-1))
}
func main() {
exampleUserDefinedPanic()
exampleBuiltinPanic()
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
}In this example, exampleUserDefinedPanic and exampleBuiltinPanic functions trigger user-defined and built-in panics respectively. The main function uses a deferred function to recover from these panics and print the recovered values.
What is the purpose of a panic in Go?
What does the recover function do?