基本示例:
package main //定义错误 //error 也是个接口 import ( "errors" "fmt" ) var errNotFound error = errors.New("Not found error") func main() { fmt.Printf("error:%v", errNotFound) }
错误处理:
package main import ( "fmt" "os" "time" ) type PathError struct { path string op string createTime string message string } func (p *PathError) Error() string { return fmt.Sprintf("path=%s op=%s createTime=%s message=%s", p.path, p.op, p.createTime, p.message) } func Open(filename string) error { file, err := os.Open(filename) if err != nil { return &PathError{ path: filename, op: "read", message: err.Error(), createTime: fmt.Sprintf("%v", time.Now()), } } defer file.Close() return nil } func main() { err := Open("D:/project/src/go_dev/day7/example10/123.txt") switch v := err.(type) { case *PathError: fmt.Println("get path error,", v) default: } }
练习
package main import "fmt" func badCall() { panic("bad end") } func test() { defer func() { if e := recover(); e != nil { fmt.Printf("Panicking%s\r\n", e) } }() badCall() fmt.Printf("After bad call\r\n") } func main() { fmt.Printf("Calling test\r\n") test() }
有疑问加站长微信联系(非本文作者)