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