Golang错误处理类型不匹配

huangapple go评论77阅读模式
英文:

golang error handling types mismatched

问题

我正在尝试学习在Go语言中的错误处理,以了解错误处理的工作原理。我有以下代码:

var a int8
var b int32    
var err error
c := a + b //类型不匹配的错误
if err != nil {
    fmt.Println(err)
}

当我尝试在vim中使用:GoRun运行时,我会得到类型不匹配的错误。

我的问题是,我如何捕捉这个错误并将消息打印到屏幕上,如果可能的话,因为错误发生在编译过程中?

英文:

I trying to learn error handling in golang to understand how error handling works. I have the following code:

var a int8
var b int32    
var err error
c := a + b //types mismatched error
if err != nil {
    fmt.Println(err)
}

when I try to run this from within vim with :GoRun I get types mismatched error.

My question is how do I catch that error and print message to screen if this is even possible as the error occurs during compiling?

答案1

得分: 1

在Go语言中,尝试将两种不同类型相加会导致编译时错误。程序将永远无法编译,因此也无法运行,所以没有什么可以捕捉的,除非在编写程序时。

只有在从函数返回时才会检查err。在这里没有函数,所以你的err永远不会被设置(除了你的代码无法编译之外)。

这与JavaScript或Perl等语言不同,这些语言没有严格的类型检查,因此在这种情况下会出现运行时错误。

英文:

Trying to add two different types in Go is a compile-time error. The program will never compile, and therefore never run, so there's nothing to catch--except when writing your program.

You'll only check err when it's returned from a function. You have no function here, so your err is never set (aside from the fact that your code won't compile).

This is different from languages like JavaScript or Perl, which don't have strict type checking, so you do get runtime errors with things like this.

huangapple
  • 本文由 发表于 2017年4月4日 06:40:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/43195476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定