Russ Cox | 57eb06f | 2012-02-16 23:51:04 -0500 | [diff] [blame] | 1 | // run |
Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 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 | |
Russ Cox | 44526cd | 2011-11-01 22:06:05 -0400 | [diff] [blame] | 14 | import "strings" |
Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 15 | |
| 16 | var x = make([]byte, 10) |
| 17 | |
| 18 | func main() { |
| 19 | test1() |
| 20 | test2() |
| 21 | test3() |
| 22 | test4() |
| 23 | test5() |
| 24 | test6() |
| 25 | test7() |
| 26 | } |
| 27 | |
| 28 | func mustRecover(s string) { |
| 29 | v := recover() |
| 30 | if v == nil { |
| 31 | panic("expected panic") |
| 32 | } |
Russ Cox | 44526cd | 2011-11-01 22:06:05 -0400 | [diff] [blame] | 33 | if e := v.(error).Error(); strings.Index(e, s) < 0 { |
Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 34 | panic("want: " + s + "; have: " + e) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func test1() { |
| 39 | defer mustRecover("index") |
| 40 | println(x[123]) |
| 41 | } |
| 42 | |
| 43 | func test2() { |
| 44 | defer mustRecover("slice") |
| 45 | println(x[5:15]) |
| 46 | } |
| 47 | |
| 48 | func test3() { |
| 49 | defer mustRecover("slice") |
Russ Cox | 9bac9d2 | 2010-08-03 00:26:02 -0700 | [diff] [blame] | 50 | var lo = 11 |
| 51 | var hi = 9 |
| 52 | println(x[lo:hi]) |
Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 53 | } |
| 54 | |
| 55 | func test4() { |
| 56 | defer mustRecover("interface") |
| 57 | var x interface{} = 1 |
Russ Cox | f2b5a07 | 2011-01-19 23:09:00 -0500 | [diff] [blame] | 58 | println(x.(float32)) |
Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 59 | } |
| 60 | |
| 61 | type T struct { |
| 62 | a, b int |
Russ Cox | 196b663 | 2011-12-12 22:22:09 -0500 | [diff] [blame] | 63 | c []int |
Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 64 | } |
| 65 | |
| 66 | func test5() { |
| 67 | defer mustRecover("uncomparable") |
| 68 | var x T |
| 69 | var z interface{} = x |
| 70 | println(z != z) |
| 71 | } |
| 72 | |
| 73 | func test6() { |
| 74 | defer mustRecover("unhashable") |
| 75 | var x T |
| 76 | var z interface{} = x |
| 77 | m := make(map[interface{}]int) |
| 78 | m[z] = 1 |
| 79 | } |
| 80 | |
| 81 | func test7() { |
Russ Cox | 21ff75b | 2010-06-18 15:46:00 -0700 | [diff] [blame] | 82 | defer mustRecover("divide by zero") |
| 83 | var x, y int |
Russ Cox | f75d0d2 | 2010-04-01 22:31:27 -0700 | [diff] [blame] | 84 | println(x / y) |
| 85 | } |