Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 1 | // $G $D/$F.go && $L $F.$A && ./$A.out |
| 2 | |
| 3 | // Copyright 2010 The Go Authors. All rights reserved. |
| 4 | // Use of this source code is governed by a BSD-style |
| 5 | // license that can be found in the LICENSE file. |
| 6 | |
| 7 | // Test of recover for run-time errors. |
| 8 | |
| 9 | // TODO(rsc): |
Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 10 | // null pointer accesses |
| 11 | |
| 12 | package main |
| 13 | |
| 14 | import ( |
| 15 | "os" |
| 16 | "strings" |
| 17 | ) |
| 18 | |
| 19 | var x = make([]byte, 10) |
| 20 | |
| 21 | func main() { |
| 22 | test1() |
| 23 | test2() |
| 24 | test3() |
| 25 | test4() |
| 26 | test5() |
| 27 | test6() |
| 28 | test7() |
| 29 | } |
| 30 | |
| 31 | func mustRecover(s string) { |
| 32 | v := recover() |
| 33 | if v == nil { |
| 34 | panic("expected panic") |
| 35 | } |
| 36 | if e := v.(os.Error).String(); strings.Index(e, s) < 0 { |
| 37 | panic("want: " + s + "; have: " + e) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | func test1() { |
| 42 | defer mustRecover("index") |
| 43 | println(x[123]) |
| 44 | } |
| 45 | |
| 46 | func test2() { |
| 47 | defer mustRecover("slice") |
| 48 | println(x[5:15]) |
| 49 | } |
| 50 | |
| 51 | func test3() { |
| 52 | defer mustRecover("slice") |
Russ Cox | 9bac9d2 | 2010-08-03 00:26:02 -0700 | [diff] [blame] | 53 | var lo = 11 |
| 54 | var hi = 9 |
| 55 | println(x[lo:hi]) |
Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 56 | } |
| 57 | |
| 58 | func test4() { |
| 59 | defer mustRecover("interface") |
| 60 | var x interface{} = 1 |
Russ Cox | f2b5a07 | 2011-01-19 23:09:00 -0500 | [diff] [blame] | 61 | println(x.(float32)) |
Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 62 | } |
| 63 | |
| 64 | type T struct { |
| 65 | a, b int |
| 66 | } |
| 67 | |
| 68 | func test5() { |
| 69 | defer mustRecover("uncomparable") |
| 70 | var x T |
| 71 | var z interface{} = x |
| 72 | println(z != z) |
| 73 | } |
| 74 | |
| 75 | func test6() { |
| 76 | defer mustRecover("unhashable") |
| 77 | var x T |
| 78 | var z interface{} = x |
| 79 | m := make(map[interface{}]int) |
| 80 | m[z] = 1 |
| 81 | } |
| 82 | |
| 83 | func test7() { |
Russ Cox | 21ff75b | 2010-06-18 15:46:00 -0700 | [diff] [blame] | 84 | defer mustRecover("divide by zero") |
| 85 | var x, y int |
Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 86 | println(x / y) |
| 87 | } |