// Try to open a file named dummy.one
// for input. Return the error if it won't open.
func dummy1() error {
f,err:= os.Open("dummy.one")
if(err!=nil) {
return err
} else {
f.Close()
return nil
}
}
// Try to open a file named dummy.two
// for input. Return the error if it won't open.
func dummy2() error {
f,err:= os.Open("dummy.two")
if(err!=nil) {
return err
} else {
f.Close()
return nil
}
}
// If the error value is not nil,
// display the caller's filename and
// calling line-number. Then, display
// the error object. Return true
// if the err parameter was true.
// Otherwise, return false.
func dispErr(err error) bool {
if(err!=nil) {
_,file,line,_:=runtime.Caller(1)
fmt.Fprintf(os.Stderr,"File: %s\nLine: %d\nErr: %v\n",file,line,err)
return true
}
return false
}
func main() {
var err error
// Create an anonymous function and
// invoke it.
//
// Use conditional returns to drop out
// of the function block to simulate falling
// out of a "try" block.
//
(func() {
fmt.Println("Attempt #1")
err=dummy1()
if dispErr(err) { return }
fmt.Println("Attempt #2")
err=dummy2()
if dispErr(err) { return }
})()