blob: 9affe25d47acf8b129af03aad933ef2bae2bbfa7 [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
14import (
15 "os"
16 "strings"
17)
18
19var x = make([]byte, 10)
20
21func main() {
22 test1()
23 test2()
24 test3()
25 test4()
26 test5()
27 test6()
28 test7()
29}
30
31func 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
41func test1() {
42 defer mustRecover("index")
43 println(x[123])
44}
45
46func test2() {
47 defer mustRecover("slice")
48 println(x[5:15])
49}
50
51func test3() {
52 defer mustRecover("slice")
Russ Cox9bac9d22010-08-03 00:26:02 -070053 var lo = 11
54 var hi = 9
55 println(x[lo:hi])
Russ Coxf75d0d22010-04-01 22:31:27 -070056}
57
58func test4() {
59 defer mustRecover("interface")
60 var x interface{} = 1
Russ Coxf2b5a072011-01-19 23:09:00 -050061 println(x.(float32))
Russ Coxf75d0d22010-04-01 22:31:27 -070062}
63
64type T struct {
65 a, b int
66}
67
68func test5() {
69 defer mustRecover("uncomparable")
70 var x T
71 var z interface{} = x
72 println(z != z)
73}
74
75func 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
83func test7() {
Russ Cox21ff75b2010-06-18 15:46:00 -070084 defer mustRecover("divide by zero")
85 var x, y int
Russ Coxf75d0d22010-04-01 22:31:27 -070086 println(x / y)
87}