Files
build-web-application-with-…/11.1.md
2012-10-30 22:54:50 +08:00

31 lines
1.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 11.1 错误处理
Go语言设计的时候主要的特点是简洁、明白简洁是指语法和C类似相当的简单明白是指任何语句都是很明显的不含有任何隐式的东西Go在设计错误的时候也是一样。我们知道C语言里面返回错误是使用-1或者nil之类的返回信息表示错误但是对于使用者来说这个返回值根本不知道什么意思而Go里面当发生异常时返回一个Error类型通过前面编写的代码我们发现在Go语言里面有很多地方都使用了Error类型很多函数都有这个Error返回。例如`os.Open`函数当打开文件失败时返回一个不为nil的error
func Open(name string) (file *File, err error)
下面这个例子通过`os.Open`打开一个文件,如果出错那么会执行`log.Fatal`打印出来错误信息:
f, err := os.Open("filename.ext")
if err != nil {
log.Fatal(err)
}
其实这样的error返回在Go语言的很多内置包里面有很多我们这个小节将详细的介绍这些error是怎么设计的以及在我们设计的Web应用如何更好的处理error。
## Error类型
error类型是一个接口类型这是他的定义
type error interface {
Error() string
}
## 自定义Error
## Error检测
## 总结
## links
* [目录](<preface.md>)
* 上一节: [错误处理,调试和测试](<11.md>)
* 下一节: [使用GDB调试](<11.2.md>)