blob: ccaf8ced16b1e5f366bf0d9d502c451709e284a2 [file] [log] [blame]
Russ Coxf75d0d22010-04-01 22:31:27 -07001// $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 Coxf75d0d22010-04-01 22:31:27 -070010// null pointer accesses
11
12package main
13
Russ Cox44526cd2011-11-01 22:06:05 -040014import "strings"
Russ Coxf75d0d22010-04-01 22:31:27 -070015
16var x = make([]byte, 10)
17
18func main() {
19 test1()
20 test2()
21 test3()
22 test4()
23 test5()
24 test6()
25 test7()
26}
27
28func mustRecover(s string) {
29 v := recover()
30 if v == nil {
31 panic("expected panic")
32 }
Russ Cox44526cd2011-11-01 22:06:05 -040033 if e := v.(error).Error(); strings.Index(e, s) < 0 {
Russ Coxf75d0d22010-04-01 22:31:27 -070034 panic("want: " + s + "; have: " + e)
35 }
36}
37
38func test1() {
39 defer mustRecover("index")
40 println(x[123])
41}
42
43func test2() {
44 defer mustRecover("slice")
45 println(x[5:15])
46}
47
48func test3() {
49 defer mustRecover("slice")
Russ Cox9bac9d22010-08-03 00:26:02 -070050 var lo = 11
51 var hi = 9
52 println(x[lo:hi])
Russ Coxf75d0d22010-04-01 22:31:27 -070053}
54
55func test4() {
56 defer mustRecover("interface")
57 var x interface{} = 1
Russ Coxf2b5a072011-01-19 23:09:00 -050058 println(x.(float32))
Russ Coxf75d0d22010-04-01 22:31:27 -070059}
60
61type T struct {
62 a, b int
63}
64
65func test5() {
66 defer mustRecover("uncomparable")
67 var x T
68 var z interface{} = x
69 println(z != z)
70}
71
72func test6() {
73 defer mustRecover("unhashable")
74 var x T
75 var z interface{} = x
76 m := make(map[interface{}]int)
77 m[z] = 1
78}
79
80func test7() {
Russ Cox21ff75b2010-06-18 15:46:00 -070081 defer mustRecover("divide by zero")
82 var x, y int
Russ Coxf75d0d22010-04-01 22:31:27 -070083 println(x / y)
84}