首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Go 语言社区】在golang里实现类似try catch 的异常处理机制

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

作者头像
李海彬
发布2018-03-20 11:11:58
1.4K0
发布2018-03-20 11:11:58
举报
文章被收录于专栏:Golang语言社区Golang语言社区

此文介绍的并非 使用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!")
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2016-02-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档