Files
the-way-to-go_ZH_CN/eBook/13.2.md
2017-05-29 14:35:47 -04:00

72 lines
2.7 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.

# 13.2 运行时异常和 panic
当发生像数组下标越界或类型断言失败这样的运行错误时Go 运行时会触发*运行时 panic*,伴随着程序的崩溃抛出一个 `runtime.Error` 接口类型的值。这个错误值有个 `RuntimeError()` 方法用于区别普通错误。
`panic` 可以直接从代码初始化:当错误条件(我们所测试的代码)很严苛且不可恢复,程序不能继续运行时,可以使用 `panic` 函数产生一个中止程序的运行时错误。`panic` 接收一个做任意类型的参数通常是字符串在程序死亡时被打印出来。Go 运行时负责中止程序并给出调试信息。在示例 13.2 [panic.go](examples/chapter_13/panic.go) 中阐明了它的工作方式:
```go
package main
import "fmt"
func main() {
fmt.Println("Starting the program")
panic("A severe error occurred: stopping the program!")
fmt.Println("Ending the program")
}
```
输出如下:
```
Starting the program
panic: A severe error occurred: stopping the program!
panic PC=0x4f3038
runtime.panic+0x99 /go/src/pkg/runtime/proc.c:1032
runtime.panic(0x442938, 0x4f08e8)
main.main+0xa5 E:/Go/GoBoek/code examples/chapter 13/panic.go:8
main.main()
runtime.mainstart+0xf 386/asm.s:84
runtime.mainstart()
runtime.goexit /go/src/pkg/runtime/proc.c:148
runtime.goexit()
---- Error run E:/Go/GoBoek/code examples/chapter 13/panic.exe with code Crashed
---- Program exited with code -1073741783
```
一个检查程序是否被已知用户启动的具体例子:
```go
var user = os.Getenv("USER")
func check() {
if user == "" {
panic("Unknown user: no value for $USER")
}
}
```
可以在导入包的 init() 函数中检查这些。
当发生错误必须中止程序时,`panic` 可以用于错误处理模式:
```go
if err != nil {
panic("ERROR occurred:" + err.Error())
}
```
<u>Go panicking</u>
在多层嵌套的函数调用中调用 panic可以马上中止当前函数的执行所有的 defer 语句都会保证执行并把控制权交还给接收到 panic 的函数调用者。这样向上冒泡直到最顶层,并执行(每层的) defer在栈顶处程序崩溃并在命令行中用传给 panic 的值报告错误情况:这个终止过程就是 *panicking*
标准库中有许多包含 `Must` 前缀的函数,像 `regexp.MustComplie``template.Must`;当正则表达式或模板中转入的转换字符串导致错误时,这些函数会 panic。
不能随意地用 panic 中止程序,必须尽力补救错误让程序能继续执行。
## 链接
- [目录](directory.md)
- 上一节:[错误处理](13.1.md)
- 下一节:[从 panic 中恢复Recover](13.3.md)