目錄golang
package main import "fmt" //系統拋異常 func test0111() { a := [5]int{0, 1, 2, 3, 4} a[1] = 123 //a[10] =456 index := 10 //index out of range a[index] = 456 } //本身拋 func test222() { getCircleArea(-5) } func getCircleArea(radius float32) (area float32) { if radius < 0 { //本身拋異常 panic("您的智商已下線,半徑不能爲負數") } return 3.14 * radius * radius } //結合defer func test0333() { //延遲執行匿名函數 //(1)函數正常執行結束了 //(2)報錯中斷執行 defer func() { //recover():返回程序爲何掛了 if err := recover(); err != nil { fmt.Println(err) } }() getCircleArea(-5) fmt.Println("這裏有沒有執行") } func test444() { test0333() fmt.Println("GAME OVER") } func main() { //test0111() //test222() //test0333() test444() }
package main import ( "errors" "fmt" ) func getCircleArea(radius float32) (ret float32, err error) { if radius < 0 { err = errors.New("沙雕,半徑不能爲負數") return } ret = 3.14 * radius * radius return } func main() { ret, err := getCircleArea(-5) if err != nil { fmt.Println(err) } else { fmt.Println("ret=", ret) } }