在golang里实现类似try catch 的异常处理机制

来源:互联网 发布:vivo网络授权书怎么 编辑:程序博客网 时间:2024/05/01 17:13
本文出自:http://golang.so/

此文介绍的并非 使用panic/recover. 因为实际使用中不建议使用panic/recover.
 但try catch finally 的编程方式 还是会经常用到的。

代码如下:

package main
  
import (
   "fmt"
   "runtime"
   "os"
)
  
   // 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 }
   })()
  
   if(err!=nil) {
         // catch block equivalent
      fmt.Println("In 'catch' block")
   }
      // finally block equivalent
   fmt.Println("Done!")
}

具体请看原文 :http://golang.so/thread-18-1-1.html