go recover panic

tags: learning go programming

content

  • recover has to be put inside of a deferred function
func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("all's good")
		}
	}
	panic("No!")
}
  • the above code works, because defer means the code will be run before the function returns, no matter what (even if the function panics)

  • in the case where recover() is not in defer

    • if recover is before panic, it doesn’t do anything cuz no panic yet
    • if it’s after panic, it won’t even be executed, cuz the code panics and passes the panic to the call stack before it could be executed

up

down

reference