相关疑难解决方法(0)

在Golang捕捉恐慌

使用以下代码,如果没有给出文件参数,则会panic: runtime error: index out of range按预期为第9行引发混乱.

我怎样才能"抓住"这种恐慌并在直接传递某些东西时处理它(os.Args[1])导致恐慌?很像PHP中的try/catch或者Python中的try/except.

我在StackOverflow上搜索了一下,但是我找不到任何可以解决这个问题的东西.

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Open(os.Args[1])
    if err != nil {
        fmt.Println("Could not open file")
    }
    fmt.Printf("%s", file)
}
Run Code Online (Sandbox Code Playgroud)

error-handling exception-handling go

45
推荐指数
6
解决办法
6万
查看次数

标签 统计

error-handling ×1

exception-handling ×1

go ×1