如何在Go中调用os.Open(<filename>)时检查错误?

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

how do I check for errors when calling os.Open(<filename>) in Go?

问题

我是新手Go(到目前为止花了30分钟!)并且正在尝试进行文件I/O。

  file, ok := os.Open("../../sample.txt")
  if ok != nil {
    // 错误处理代码在这里
    os.Exit(1)
  }
  ... 

当调用失败时,它不应该返回一个错误号码吗?这个调用返回os.Error,它除了'String()'之外没有其他方法。

这是在Go中检查错误的推荐方式吗?

英文:

I'm new to Go (spent 30mins so far!) and am trying to do File I/O.

  file, ok := os.Open(&quot;../../sample.txt&quot;)
  if ok != nil {
    // error handling code here
    os.Exit(1)
  }
  ... 

When the call fails, shouldn't it return an error number? This call returns os.Error and it has no methods other than 'String()'.

Is this the recommended way to check for errors in Go?

答案1

得分: 3

典型的Go代码(使用os包)没有分析返回的错误对象。它只是将错误消息打印给用户(用户根据打印的消息知道出了什么问题)或将错误原样返回给调用者。

如果您想防止程序打开不存在的文件,或者想检查文件是否可读/可写,我建议在打开文件之前使用os.Stat函数进行检查。

您可以分析返回的错误的Go类型,但这似乎不方便:

package main

import "fmt"
import "os"

func main() {
    _, err := os.Open("non-existent")
    if err != nil {
        fmt.Printf("err has type %T\n", err)
        if err2, ok := err.(*os.PathError); ok {
            fmt.Printf("err2 has type %T\n", err2.Error)
            if errno, ok := err2.Error.(os.Errno); ok {
                fmt.Fprintf(os.Stderr, "errno=%d\n", int64(errno))
            }
        }

        fmt.Fprintf(os.Stderr, "%s\n", err)
        os.Exit(1)
    }
}

输出结果为:

err has type *os.PathError
err2 has type os.Errno
errno=2
open non-existent: no such file or directory
英文:

Typical Go code (which uses the <code>os</code> package) is not analyzing the returned error object. It just prints the error message to the user (who then knows what went wrong based on the printed message) or returns the error as-is to the caller.

If you want to prevent your program from opening a non-existent file, or want to check whether the file is readable/writable, I wound suggest to use the os.Stat function prior to opening the file.

Your can analyze the Go type of the returned error, but this seems inconvenient:

package main

import &quot;fmt&quot;
import &quot;os&quot;

func main() {
    _, err := os.Open(&quot;non-existent&quot;)
    if err != nil {
        fmt.Printf(&quot;err has type %T\n&quot;, err)
        if err2, ok := err.(*os.PathError); ok {
            fmt.Printf(&quot;err2 has type %T\n&quot;, err2.Error)
            if errno, ok := err2.Error.(os.Errno); ok {
                fmt.Fprintf(os.Stderr, &quot;errno=%d\n&quot;, int64(errno))
            }
        }

        fmt.Fprintf(os.Stderr, &quot;%s\n&quot;, err)
        os.Exit(1)
    }
}

which prints:

err has type *os.PathError
err2 has type os.Errno
errno=2
open non-existent: no such file or directory

答案2

得分: 0

是的,这是Go语言中的常规方式(多值返回),Go语言的开发者对异常有不同的看法,并以这种方式处理它。

阅读这个链接:

http://www.softmachinecubed.com/tech/2009/12/6/googles-go-language-multi-value-return-vs-exceptions-c.html

英文:

Yes this is the normal way in Go (multi-value return), the makers of Go have a different view on Exceptions and handle it in this way.

Read this:

http://www.softmachinecubed.com/tech/2009/12/6/googles-go-language-multi-value-return-vs-exceptions-c.html

huangapple
  • 本文由 发表于 2011年12月22日 04:40:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/8596074.html
匿名

发表评论

匿名网友

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

确定