This repository demonstrates the use of panic
along with recover
in Go. It showcases how a panicking program can regain control using the recover
function within a deferred function, preventing the program from crashing.
- This example covers the usage of `panic` and `recover` in Go.
- The `panic` function triggers a panic, which begins unwinding the stack, while the `recover` function is used to catch the panic and allow the program to continue executing.
- This technique can be used to handle unexpected errors and avoid abrupt termination of the program.
package main
import (
"fmt"
)
func main() {
// The recover function is used to regain control of a panicking goroutine.
// It can be used within a deferred function to catch a panic and prevent the program from crashing
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
fmt.Println("Starting main")
panic("A severe error occurred")
fmt.Println("This will not be printed")
}
-
Make sure you have Go installed. If not, you can download it from here.
-
Clone this repository:
git clone https://github.com/Rapter1990/go_sample_examples.git
-
Navigate to the
027_panic_and_defer/005_panic_with_recover
directory:cd go_sample_examples/027_panic_and_defer/005_panic_with_recover
-
Run the Go program:
go run main.go
When you run the program, you should see the following output:
Starting main
Recovered from panic: A severe error occurred