欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > Go语言入门到入土——三、处理并返回异常

Go语言入门到入土——三、处理并返回异常

2025/4/19 18:08:35 来源:https://blog.csdn.net/m0_46295679/article/details/147295082  浏览:    关键词:Go语言入门到入土——三、处理并返回异常

Go语言入门到入土——三、处理并返回异常


文章目录

  • Go语言入门到入土——三、处理并返回异常
  • 1. 在greetings.go中添加异常处理代码
  • 2. 在hello.go中添加日志记录代码
  • 3. 运行


1. 在greetings.go中添加异常处理代码

处理空输入的异常,代码如下:

package greetingsimport ("errors""fmt"
)// Hello returns a greeting for the named person.
func Hello(name string) (string, error) {// If no name was given, return an error with a message.if name == "" {return "", errors.New("empty name")}// If a name was received, return a value that embeds the name// in a greeting message.message := fmt.Sprintf("Hi, %v. Welcome!", name)return message, nil
}

2. 在hello.go中添加日志记录代码

记录空异常的日志代码如下:

package mainimport ("fmt""log""example.com/greetings"
)func main() {// Set properties of the predefined Logger, including// the log entry prefix and a flag to disable printing// the time, source file, and line number.log.SetPrefix("greetings: ")log.SetFlags(0)// Request a greeting message.message, err := greetings.Hello("")// If an error was returned, print it to the console and// exit the program.if err != nil {log.Fatal(err)}// If no error was returned, print the returned message// to the console.fmt.Println(message)
}

3. 运行

go run main.go

结果如下:

greetings: empty name
exit status 1

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词