How do you catch panic in Golang?
Golang official packages use panic/defer+recover as throw/catch, but only when they need to unwind a large call stack. The "idiomatic" solution is to check the parameters before using them.
When a program panics, the current function stops running, and the program prints a log message and crashes.
You can cause a panic yourself simply by calling the built-in panic function.
If you want to catch anything you can do:
Example
package main
import (
"fmt"
"os"
)
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Fprintf(os.Stderr, "Exception: %v\n", err)
os.Exit(1)
}
}()
file, err := os.Open(os.Args[1])
if err != nil {
fmt.Println("Could not open file")
}
fmt.Printf("%s", file)
}
Exception: runtime error: index out of range [1] with length 1
exit status 1
Most Helpful This Week
Golang program for implementation of Longest Common Sub-sequence
How to check if an item exists in Slice in Golang?
Golang program for implementation of Floyd–Warshall Algorithm
How to use WaitGroup to delay execution of the main function until after all goroutines are complete.
How do you set headers in an HTTP response in Go?
How do you handle HTTP timeouts with an HTTP client in Go?