This recovery works:
func TestSomeTest(t *testing.T) {
defer func() {
r := recover()
fmt.Println("recovery")
fmt.Println(r)
}()
panic("panic here")
}
But this does not:
func TestSomeTest(t *testing.T) {
panic("panic here")
}
func TestMain(m *testing.M) {
defer func() {
r := recover()
fmt.Println("recovery")
fmt.Println(r)
}()
ret := m.Run()
os.Exit(ret)
}
Why?
I expect that panic here
will be recovered by code in func TestMain(m *testing.M)
. Why not? I just have panic
without any recovery
in this case.
Full code:
package main
import (
"fmt"
"os"
"testing"
)
func TestSomeTest(t *testing.T) {
// defer func() {
// r := recover()
// fmt.Println("recovery")
// fmt.Println(r)
// }()
panic("panic here")
}
func TestMain(m *testing.M) {
defer func() {
r := recover()
fmt.Println("recovery")
fmt.Println(r)
}()
ret := m.Run()
os.Exit(ret)
}
To run this code I used go test
command.
In the go language recover function is used to handle any unexpected error, recovery is similar to try catch of other programming language, mostly we use the recover where we are not sure about the error and we do not want our program to stop execution (in case if exception occurs in mean time of execution of the ...
The recover() function in Go Language is used to recover from a goroutine that is in panic, meaning it helps recover from an error that has been raised. The program takes control through recover rather than letting the code crash. recover() is an inbuilt function in Go Language.
Recover and catch a panicThe built-in recover function can be used to regain control of a panicking goroutine and resume normal execution. A call to recover stops the unwinding and returns the argument passed to panic . If the goroutine is not panicking, recover returns nil .
The panic() function in Go Language is similar to exceptions raised at runtime when an error is encountered. panic() is either raised by the program itself when an unexpected error occurs or the programmer throws the exception on purpose for handling particular errors.
It's because the tests are run in separate goroutines.
It's like if your fist example sent off a goroutine, which can't be recovered.
func TestSomeTest(t *testing.T) {
defer func() {
r := recover()
fmt.Println("recovery")
fmt.Println(r)
}()
go func() {
// won't recover
panic("panic here")
}()
time.Sleep(time.Second)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With