Recover in Go
Go: Recover
What is Recover?
In Go, the recover function is used to handle panics by catching and recovering from them. When a panic occurs, the Go runtime searches for a deferred recover call in the current goroutine and executes it if found. The recover function returns the value passed to the panic call that triggered the panic, allowing you to inspect and potentially recover from the panic.
How recover works in Go
Here's an example to demonstrate how recover works in Go:
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered:", r)
}
}()
panic("Oops! Something went wrong...")
}
Explaination: we've defined an anonymous function that will be deferred until the end of the main function. Inside this function, we call the recover function and check if it returns a non-nil value. If it does, we print a message indicating that we've recovered from a panic and print the value that was passed to the panic function.
We then deliberately trigger a panic by calling panic with a string message. This will cause the program to exit unless we recover from the panic using the recover function.
When we run this program, we'll see the following output:
Recovered: Oops! Something went wrong...
- The recover function successfully catches the panic and allows us to handle it gracefully by printing a message instead of abruptly terminating the program.
- It's important to note that the recover function only works within a deferred function. If you call it outside of a deferred function, it will simply return nil. Additionally, calling recover multiple times within the same deferred function will only catch the first panic that occurred.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go