Sword of GF
Sword of GF

Reputation: 171

Golang handling nil pointer exceptions

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?

Upvotes: 7

Views: 20122

Answers (2)

OneOfOne
OneOfOne

Reputation: 99224

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))
}

Upvotes: 14

chendesheng
chendesheng

Reputation: 2129

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.

Upvotes: 2

Related Questions