error--
2016-01-21 19:22
218 查看
第一次看这个,觉的比较难懂,后续需要继续看
package
main
package
main
import "errors"
import "fmt"
//By convention, errors are the last return value and have type error, a built-in interface.
func f1(arg int) (int, error) {
if arg == 42 {
//errors.New constructs a basic error value with the given error message.
return -1, errors.New("can't work with 42")
}
//A nil value in the error position indicates that there was no error.
return arg + 3, nil
}
//It’s possible to use custom types as errors by implementing the Error() method on them. Here’s a variant on the example above that uses a custom type to explicitly represent an argument error.
type argError struct {
arg int
prob string
}
func (e *argError) Error() string {
return fmt.Sprintf("%d - %s", e.arg, e.prob)
}
func f2(arg int) (int, error) {
if arg == 42 {
//In this case we use &argError syntax to build a new struct, supplying values for the two fields arg and prob.
return -1, &argError{arg, "can't work with it"}
}
return arg + 3, nil
}
func main() {
//The two loops below test out each of our error-returning functions. Note that the use of an inline error check on the if line is a common idiom in Go code.
for _, i := range []int{7, 42} {
if r, e := f1(i); e != nil {
fmt.Println("f1 failed:", e)
} else {
fmt.Println("f1 worked:", r)
}
}
for _, i := range []int{7, 42} {
if r, e := f2(i); e != nil {
fmt.Println("f2 failed:", e)
} else {
fmt.Println("f2 worked:", r)
}
}
//If you want to programmatically use the data in a custom error, you’ll need to get the error as an instance of the custom error type via type assertion.
_, e := f2(42)
if ae, ok := e.(*argError); ok {
fmt.Println(ae.arg)
fmt.Println(ae.prob)
}
}
相关文章推荐
- ns3::UnixDatagramSocketFd::DoRecvmsg
- Java问题定位
- C# .NET开发图形图像程序时提示"GDI+ 中发生一般性错误"
- Java基础_11_网络编程
- I2S 技术相关
- SQLiteDatabase类——转载(http://www.cnblogs.com/tt_mc/archive/2010/03/09/1681540.html)
- AIX安装数据库软件拒绝根目录
- 设置table的td宽度,不随文字变宽
- 在linux下使用转码器(音频转码)
- android 自定义控件 播放gif 既可以是从网络上获取资源 也可以是本地资源
- 读书笔记一
- 数据结构之链表基本操作
- MINA连接
- nodejs 基础
- 政治的玩法
- iptables 从链、表开始理解
- django 自定义模板标签和过滤器
- ffmpeg 关键帧截图
- python 文件中的__name__是什么?
- 在django模板中定义变量(set variable in django template)