Catching panics in Golang

后端 未结 7 2010
自闭症患者
自闭症患者 2021-01-31 07:24

With the following code, if no file argument is given, a panic is thrown for line 9 panic: runtime error: index out of range as expected.

How can I \'catch\

相关标签:
7条回答
  • 2021-01-31 08:00

    Go is not python, you should properly check for args before you use it:

    func main() {
        if len(os.Args) != 2 {
             fmt.Printf("usage: %s [filename]\n", os.Args[0])
             os.Exit(1)
        }
        file, err := os.Open(os.Args[1])
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s", file)
    }
    
    0 讨论(0)
提交回复
热议问题