错误
package err_test
import (
"errors"
"testing"
)
var LessThanTwoError = errors.New("n should be not less than 2")
var LargerThenHundredError = errors.New("n should be not larger than 100")
func GetFibonacci(n int) ([]int, error) {
if n < 2 {
return nil, LessThanTwoError
}
if n > 100 {
return nil, LargerThenHundredError
}
fibList := []int{1, 1}
for i := 2; /*短变量声明 := */ i < n; i++ {
fibList = append(fibList, fibList[i-2]+fibList[i-1])
}
return fibList, nil
}
func TestGetFibonacci(t *testing.T) {
if v, err := GetFibonacci(128); err != nil {
if err == LargerThenHundredError {
t.Log("Error LargerThenHundredError")
}
t.Error(err)
} else {
t.Log(v)
}
}
panic
package panic_recover
import (
// "errors"
"fmt"
"os"
"testing"
)
func TestPanicVxExit(t *testing.T) {
defer func() {
if err := recover(); err != nil {
fmt.Println("recovered from ", err)
}
}()
fmt.Println("Start")
//panic(errors.New("Something wrong!"))
os.Exit(-1)
fmt.Println("End")
}
执行到panic时,后面的不会继续执行,按照defer函数列表逆序执行,defer里可用recover捕获panic; os.Exit(-1)执行后不会执行defer
网友评论