From e5b570dc8253c25071e3b91f7ea8b0fd8f258cfb Mon Sep 17 00:00:00 2001 From: Robert Griesemer Date: Fri, 20 Nov 2009 11:50:11 -0800 Subject: Support for basic try-catch style exception handling. Meant as illustration of the Go pattern that is using goroutines and channels to handle exceptional situations. Note: There is no need for "Finally" since the "try block" (the function f supplied to Try) cannot do a Smalltalk-style non-local return and terminate the function surrounding Try. Replaces CL 157083. R=r, rsc http://codereview.appspot.com/157087 --- src/pkg/exp/exception/exception_test.go | 61 +++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/pkg/exp/exception/exception_test.go (limited to 'src/pkg/exp/exception/exception_test.go') diff --git a/src/pkg/exp/exception/exception_test.go b/src/pkg/exp/exception/exception_test.go new file mode 100644 index 000000000..91f742ea0 --- /dev/null +++ b/src/pkg/exp/exception/exception_test.go @@ -0,0 +1,61 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package exception + +import "testing" + +func TestNoException(t *testing.T) { + e := Try(func(throw Handler) {}); + if e != nil { + t.Fatalf("no exception expected, found: %v", e) + } +} + + +func TestNilException(t *testing.T) { + e := Try(func(throw Handler) { throw(nil) }); + if e == nil { + t.Fatalf("exception expected", e) + } + if e.Value != nil { + t.Fatalf("nil exception expected, found: %v", e) + } +} + + +func TestTry(t *testing.T) { + s := 0; + for i := 1; i <= 10; i++ { + e := Try(func(throw Handler) { + if i%3 == 0 { + throw(i); + panic("throw returned"); + } + }); + if e != nil { + s += e.Value.(int) + } + } + result := 3 + 6 + 9; + if s != result { + t.Fatalf("expected: %d, found: %d", result, s) + } +} + + +func TestCatch(t *testing.T) { + s := 0; + for i := 1; i <= 10; i++ { + Try(func(throw Handler) { + if i%3 == 0 { + throw(i) + } + }).Catch(func(x interface{}) { s += x.(int) }) + } + result := 3 + 6 + 9; + if s != result { + t.Fatalf("expected: %d, found: %d", result, s) + } +} -- cgit v1.2.3