I see a lot of examples using defer func() inside of a function. Is there a way to keep from repeating it in various places and call it like a normal function?
In this example (and many others) the defer function is nested inside of another function:
package main
import (
"fmt"
"os"
)
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Fprintf(os.Stderr, "Exception: %v
", err)
os.Exit(1)
}
}()
file, err := os.Open(os.Args[1])
if err != nil {
fmt.Println("Could not open file")
}
fmt.Printf("%v", file)
}
Is there a way to move the defer func() outside of main() so it can be used by other functions as well?