learning target
Master error handling
Master custom error handling
Mastering defer keyword
Error Handling
GO no exception handling mechanism
Go language introduces a standard mode on error handling, error i.e. the interface, the interface is defined as follows:
type interface error {
Error() string
}
You can create instances rapid error by errors.New
errors.New("错误信息")
func Foo(param int)(n int, err error) {
// ...
}
//调用时的代码建议按如下方式处理错误情况:
n, err := Foo(0)
if err != nil {
// 错误处理
} else {
// 使用返回值n
}
Custom error type
defer keyword
func CopyFile(dst, src string) (w int64, err error) {
srcFile, err := os.Open(src)
if err != nil {
return
}
defer srcFile.Close()
dstFile, err := os.Create(dstName)
if err != nil {
return
}
defer dstFile.Close()
return io.Copy(dstFile, srcFile)
}
Similar to Java's finally in
There may be a plurality of function defer statement
Call to defer statement is in compliance with last-out principle, that the latter statement will defer the first to be executed.
painc与recover
Error recovery may not be used for panic
Before panic exit will defer the implementation of the specified content
Error Recovery
defer func() {
if err :=recover();err != nil {
//恢复错误
}
}()
os.Exit exit
os.Exit terminate the program does not directly call the function specified defer
Output current information does not call stack when os.Exit exit
**** If the code word is not easy to have to help you Give me a concern ****
**** love life love technology QQ group: 894 109 590 ****