Skip to content

Instantly share code, notes, and snippets.

@acook
Last active February 20, 2021 01:42
Show Gist options
  • Save acook/243c9ffc871af261d9ab to your computer and use it in GitHub Desktop.
Save acook/243c9ffc871af261d9ab to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
)
func main() {
// go complains: "use of builtin recover not in function call"
//defer cleanup_broken()
// this functions correctly
cleanup()
}
func cleanup_broken() {
if r := recover; r != nil {
fmt.Println("encountered an error and had to quit", r)
os.Exit(1)
}
}
func cleanup() {
if r := recover(); r != nil {
fmt.Println("encountered an error and had to quit", r)
os.Exit(1)
}
}
@acook
Copy link
Author

acook commented Feb 7, 2021

Yep! Since recover is a built-in function, the call to recover will fail with compilation error. Hence we should always invoke the function as recover()

It's been 6 years since I posted this. How did you stumble across it?

@gandharvas
Copy link

Yep! Since recover is a built-in function, the call to recover will fail with compilation error. Hence we should always invoke the function as recover()

It's been 6 years since I posted this. How did you stumble across it?

Actually I was bought here through search result, when I was searching for recover and panic :)

@acook
Copy link
Author

acook commented Feb 20, 2021

Cool, hope it was helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment