【Go 语言社区】在golang里实现类似try catch 的异常处理机制

时间:2022-05-04
本文章向大家介绍【Go 语言社区】在golang里实现类似try catch 的异常处理机制,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

此文介绍的并非 使用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: %snLine: %dnErr: %vn",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!")
}