本文介绍了在高隆赶上恐慌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用以下代码,如果没有给出文件参数,则会抛出第9行的紧急情况 panic:runtime error:index out of range
as expected。
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.
我如何抓住这个恐慌,直接传递给它时处理它( os.Args [1]
)导致恐慌?很像PHP中的try / catch或者在Python中尝试/除外。
How can I 'catch' this panic and handle it when directly when passing something to it (os.Args[1]
) that causes the panic? Much like try/catch in PHP or try/except in Python.
我在StackOverflow上搜索了一下,但是我没有找到任何答案。
I've had a search here on StackOverflow but I've not found anything that answers this as such.
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)
}
推荐答案
Go不是python,你应该在使用它之前正确检查args:
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)
}
这篇关于在高隆赶上恐慌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!