Просмотр исходного кода

Merge pull request #178 from dake/master

翻译13.2
Unknwon 10 лет назад
Родитель
Сommit
801aa90628
7 измененных файлов с 293 добавлено и 1 удалено
  1. 3 0
      .gitignore
  2. 1 1
      eBook/13.1.md
  3. 74 0
      eBook/13.2.md
  4. 84 0
      eBook/13.3.md
  5. 126 0
      eBook/13.4.md
  6. 2 0
      eBook/13.5.md
  7. 3 0
      eBook/directory.md

+ 3 - 0
.gitignore

@@ -25,3 +25,6 @@ the-way-to-go.sublime-project
 the-way-to-go.sublime-workspace
 
 *.pdf
+
+*.html
+*.htm

+ 1 - 1
eBook/13.1.md

@@ -197,5 +197,5 @@ if len(os.Args) > 1 && (os.Args[1] == “-h” || os.Args[1] == “--help”) {
 ## 链接
 
 - [目录](directory.md)
-- 上一节:[错误处理与测试](12.12.md)
+- 上一节:[错误处理与测试](13.0.md)
 - 下一节:[运行时异常和 panic](13.2.md)

+ 74 - 0
eBook/13.2.md

@@ -1,2 +1,76 @@
 # 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)

+ 84 - 0
eBook/13.3.md

@@ -0,0 +1,84 @@
+# 13.3 从 panic 中恢复 (Recover)
+
+正如名字一样,这个(recover)内建函数被用于从 panic 或 错误场景中恢复:让程序可以从 panicking 重新获得控制权,停止终止过程进而恢复正常执行。
+
+`recover` 只能在 defer 修饰的函数(参见 6.4 节)中使用:用于取得 panic 调用中传递过来的错误值,如果是正常执行,调用 `recover` 会返回 nil,且没有其它效果。
+
+<u>总结</u>:panic 会导致栈被展开直到 defer 修饰的 recover() 被调用或者程序中止。
+
+下面例子中的 protect 函数调用函数参数 g 来保护调用者防止从 g 中抛出的运行时 panic,并展示 panic 中的信息:
+
+```go
+func protect(g func()) {
+	defer func() {
+		log.Println(“done”)
+		// Println executes normally even if there is a panic 
+		if err := recover(); err != nil {
+		log.Printf(“run time panic: %v”, err)
+		}
+	}()
+	log.Println(“start”)
+	g() //   possible runtime-error
+}
+
+```
+
+这跟 Java 和 .NET 这样的语言中的 catch 块类似。
+
+log 包实现了简单的日志功能:默认的 log 对象向标准错误输出中写入并打印每条日志信息的日期和时间。除了 `Println` 和 `Printf` 函数,其它的致命性函数都会在写完日志信息后调用 os.Exit(1),那些退出函数也是如此。而 Panic 效果的函数会在写完日志信息后调用 panic;可以在程序必须中止或发生了临界错误时使用它们,就像当 web 服务器不能启动时那样(参见 15.4 节中的例子)。
+
+log 包用那些方法(methods)定义了一个 Logger 接口类型,如果你想自定义日志系统的话可以参考(参见 [http://golang.org/pkg/log/#Logger](http://golang.org/pkg/log/#Logger))。
+
+这是一个展示 panic,defer 和 recover 怎么结合使用的完整例子:
+
+示例 13.3 [panic_recover.go](examples/chapter_13/panic_recover.go):
+
+```go
+// panic_recover.go
+package main
+
+import (
+	"fmt"
+)
+
+func badCall() {
+	panic("bad end")
+}
+
+func test() {
+	defer func() {
+		if e := recover(); e != nil {
+			fmt.Printf("Panicing %s\r\n", e)
+		}
+	}()
+	badCall()
+	fmt.Printf("After bad call\r\n") // <-- wordt niet bereikt
+}
+
+func main() {
+	fmt.Printf("Calling test\r\n")
+	test()
+	fmt.Printf("Test completed\r\n")
+}
+
+```
+
+输出:
+
+```
+Calling test
+Panicing bad end
+Test completed
+
+```
+
+`defer-panic-recover` 在某种意义上也是一种像 `if`,`for` 这样的控制流机制。
+
+Go 标准库中许多地方都用了这个机制,例如,json 包中的解码和 regexp 包中的 Complie 函数。Go 库的原则是即使在包的内部使用了 panic,在它的对外接口(API)中也必须用 recover 处理成返回显式的错误。
+
+
+## 链接
+
+- [目录](directory.md)
+- 上一节:[错运行时异常和 panic](13.2.md)
+- 下一节:[自定义包中的错误处理和 panicking](13.4.md)

+ 126 - 0
eBook/13.4.md

@@ -0,0 +1,126 @@
+# 13.4 自定义包中的错误处理和 panicking
+
+这是所有自定义包实现者应该遵守的最佳实践:
+
+1)*在包内部,总是应该从 panic 中 recover*:不允许显式的超出包范围的 panic()
+
+2)*向包的调用者返回错误值(而不是 panic)。*
+
+在包内部,特别是在非导出函数中有很深层次的嵌套调用时,对主调函数来说用 panic 来表示应该被翻译成错误的错误场景是很有用的(并且提高了代码可读性)。
+
+这在下面的代码中被很好地阐述了。我们有一个简单的 parse 包(示例 13.4)用来把输入的字符串解析为整数切片;这个包有自己特殊的 `ParseError`。
+
+当没有东西需要转换或者转换成整数失败时,这个包会 panic(在函数 fields2numbers 中)。但是可导出的 Parse 函数会从 panic 中 recover 并用所有这些信息返回一个错误给调用者。为了演示这个过程,在 panic_recover.go 中 调用了 parse 包(示例 13.4);不可解析的字符串会导致错误并被打印出来。
+
+示例 13.4 [parse.go](examples/chapter_13/parse/parse.go):
+
+```go
+// parse.go
+package parse
+
+import (
+	"fmt"
+	"strings"
+	"strconv"
+)
+
+// A ParseError indicates an error in converting a word into an integer.
+type ParseError struct {
+        Index int      // The index into the space-separated list of words.
+        Word  string   // The word that generated the parse error.
+        Err error // The raw error that precipitated this error, if any.
+}
+
+// String returns a human-readable error message.
+func (e *ParseError) String() string {
+        return fmt.Sprintf("pkg parse: error parsing %q as int", e.Word)
+}
+
+// Parse parses the space-separated words in in put as integers.
+func Parse(input string) (numbers []int, err error) {
+        defer func() {
+                if r := recover(); r != nil {
+                        var ok bool
+                        err, ok = r.(error)
+                        if !ok {
+                                err = fmt.Errorf("pkg: %v", r)
+                        }
+                }
+        }()
+
+        fields := strings.Fields(input)
+        numbers = fields2numbers(fields)
+        return
+}
+
+func fields2numbers(fields []string) (numbers []int) {
+        if len(fields) == 0 {
+                panic("no words to parse")
+        }
+        for idx, field := range fields {
+                num, err := strconv.Atoi(field)
+                if err != nil {
+                        panic(&ParseError{idx, field, err})
+                }
+                numbers = append(numbers, num)
+        }
+        return
+}
+
+```
+
+示例 13.5 [panic_package.go](examples/chapter_13/panic_package.go):
+
+```go
+// panic_package.go
+package main
+
+import (
+	"fmt"
+	"./parse/parse"
+)
+
+func main() {
+        var examples = []string{
+                "1 2 3 4 5",
+                "100 50 25 12.5 6.25",
+                "2 + 2 = 4",
+                "1st class",
+                "",
+        }
+
+        for _, ex := range examples {
+                fmt.Printf("Parsing %q:\n  ", ex)
+                nums, err := parse.Parse(ex)
+                if err != nil {
+                        fmt.Println(err) // here String() method from ParseError is used
+                        continue
+                }
+                fmt.Println(nums)
+        }
+}
+
+```
+
+输出:
+
+```
+Parsing "1 2 3 4 5":
+  [1 2 3 4 5]
+Parsing "100 50 25 12.5 6.25":
+  pkg parse: error parsing "12.5" as int
+Parsing "2 + 2 = 4":
+  pkg parse: error parsing "+" as int
+Parsing "1st class":
+  pkg parse: error parsing "1st" as int
+Parsing "":
+  pkg: no words to parse
+
+```
+
+
+## 链接
+
+- [目录](directory.md)
+- 上一节:[从 panic 中恢复 (Recover)](13.3.md)
+- 下一节:[一种用闭包处理错误的模式](13.5.md)

+ 2 - 0
eBook/13.5.md

@@ -0,0 +1,2 @@
+# 13.5 一种用闭包处理错误的模式
+

+ 3 - 0
eBook/directory.md

@@ -127,6 +127,9 @@
 - 第13章:[错误处理与测试](13.0.md)
     - 13.1 [错误处理](13.1.md)
     - 13.2 [运行时异常和 panic](13.2.md)
+    - 13.3 [从 panic 中恢复 (Recover)](13.3.md)
+    - 13.4 [自定义包中的错误处理和 panicking](13.4.md)
+    - 13.5 [一种用闭包处理错误的模式](13.5.md)
 - 第14章:goroutine 与 channel
 - 第15章:网络、模版与网页应用