Reputation: 65
I have the code as below and defer wasn't executed.
Doesn't defer work if we put it after panic?
package main
import (
"fmt"
)
func main() {
fmt.Println("begining of main")
panic("stop here")
defer fmt.Println("end of main")
}
nghiatran@nghiatran-VB:~/go/src/defer$ go run main.go
begining of main
panic: stop here
goroutine 1 [running]:
main.main()
/home/nghiatran/go/src/defer/main.go:9 +0x96
exit status 2
nghiatran@nghiatran-VB:~/go/src/defer$
Upvotes: 2
Views: 10770
Reputation: 49171
The order of statements is wrong. Defer pushes function call to the stack. At the end of the function execution stacked calls are taken in reverse order and are executed. It does not matter whether function panics or not.
You need to push the function call first and then panic.
package main
import (
"fmt"
)
func main() {
defer fmt.Println("end of main") // push the call to the stack
fmt.Println("begining of main")
panic("stop here")
// the deffered functions are called as if they where here
}
The defer
statement works differently than catch
and finally
blocks but it offer the same functionality.
Upvotes: 14
Reputation: 99
defer
won't work after panic
because the control never reached the statement, hence it was never registered. This is like printing something after a return statement in a function, it's basically an unreachable code.
Upvotes: 2