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
How to append struct member dynamically using Empty Interface?
How to check specific field exist in struct?
How to create Slice of Struct in Golang?
Concurrently printing array elements using goroutines and channels
How to build a map of struct and append values to it?
How to convert Struct fields into Map String?