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
Interface embedding and calling interface methods from another package in Go (Golang)
How do you read headers from an HTTP response with an HTTP client in Go?
Golang program for drawing a Cuboid
Nested Struct Type
How to convert Boolean Type to String in Go?
GO supports the standard arithmetic operators: (Addition, Subtraction, Multiplication, Division,Remainder)