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' 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.
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)
}
I had to catch panics in a test case. I got redirected here.
Used from https://github.com/golang/go/commit/e4f1d9cf2e948eb0f0bb91d7c253ab61dfff3a59 (ref from VonC)
We can manage panic without halting process using recover. By calling recover in any function using defer it will return the execution to calling function. Recover returns two values one is boolean and other one is interface to recover. Using type assertion we can get underlying error value You can also print underlying error using using recover.
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 withrecover
. See http://golang.org/doc/effective_go.html#recoverNote that the recover treatment of a panic Execution error (such as attempting to index an array out of bounds trigger) might change with go 1.7 after issue 14965
See CL 21214 and its test:
When you recover a panic error, you would be able to do:
This is still being evaluated, and as Dave Cheney. mentions:
Some Golang official packages use panic/defer+recover as throw/catch, but only when they need to unwind a large call stack. In Golang's json package using panic/defer+recover as throw/catch is the most elegant solution.
from http://blog.golang.org/defer-panic-and-recover
Search for
d.error(
at http://golang.org/src/encoding/json/decode.goIn your example the "idiomatic" solution is to check the parameters before using them, as other solutions have pointed.
But, if you want/need to catch anything you can do:
Go is not python, you should properly check for args before you use it: