使用以下代码,如果没有给出文件参数,则会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)