7

Consider the following code:

list := strings.Split(somestring, "\n")

Let's say this returns a list or slice of three elements. Then, if you try to access something outside the range of the slice:

someFunction(list[3])

The program can crash because of a nil pointer. Is there some way in Golang to handle a nil pointer exception so that the program won't crash and can instead respond appropriately?

4
  • 5
    You should instead check the length of the slice len(list) before accessing an index, which will prevent an out of bounds error. I would not lean on panic/recover (as suggested) for something like this. Commented Jul 21, 2014 at 2:51
  • @elithrar access list[3] should not cause a nil panic, it's index out of range Commented Jul 21, 2014 at 2:54
  • @elithrar I have a rather long list of if statements, each one expecting list[] to be a different length, so I was thinking if there was some universal way to handle an exception, such as a try catch or try except statement, then I wouldn't need to stick a call to len() in each if statement. Though it's sounding like there's no real equivalent in Golang. Commented Jul 21, 2014 at 3:05
  • Sure, make sure it never happens ;) Commented Jul 21, 2014 at 6:15

2 Answers 2

14

You can't do that in Go, and you shouldn't even if you can.

Always check your variables and slices, God kills a kitten every time you try to use an unchecked index on a slice or an array, I like kittens so I take it personally.

It's very simple to work around it, example:

func getItem(l []string, i int) (s string) {
    if i < len(l) {
        s = l[i]
    }
    return
}
func main() {
    sl := []string{"a", "b"}
    fmt.Println(getItem(sl, 1))
    fmt.Println(getItem(sl, 3))
}
Sign up to request clarification or add additional context in comments.

3 Comments

The dogma of no exceptions in go is very harmful to graceful failure. You can't just "always check your variables". Bugs will inevitably happen, and its absurd to advocate that people not be ready for that.
I also like kittens. Thank you, I'll check my variables from now on.
In Go you can recover from a nil pointer exception; it's done through the "recover" function, which is (intentionally) a bit akward to use.
2

Go has panic recover statements it works like exception in java or c#

see http://blog.golang.org/defer-panic-and-recover

Access nil pointer will cause a panic, and if you don't use recover to catch it the app will crash.

But go doesn't encourage use panic/recover to handle those exceptions, you probably should check if a pointer is nil before use it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.