Catching panics in Golang

后端 未结 7 2011
自闭症患者
自闭症患者 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 07:41

    First: You wouldn't want to do this. Try-catch-style error handling is no error handling. In Go you would check len(os.Args) first and access element 1 only if present.

    For the rare cases you need to catch panics (and your case is not one of them!) use defer in combination with recover. See http://golang.org/doc/effective_go.html#recover

提交回复
热议问题