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
Empowering Developers: Google Cloud’s Generative AI Systems
Top 20 Most Popular Cryptocurrencies To Watch In 2024
Various examples of printing and formatting in Golang
GO Program to Check Whether a Number is Palindrome or Not
GO language program with example of Array Reverse Sort Functions for integer and strings
Golang program for implementation of Bubble Sort