Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang handling nil pointer exceptions

Tags:

pointers

go

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?

like image 995
Sword of GF Avatar asked Jul 17 '26 16:07

Sword of GF


2 Answers

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))
}
like image 192
OneOfOne Avatar answered Jul 19 '26 09:07

OneOfOne


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.

like image 42
chendesheng Avatar answered Jul 19 '26 09:07

chendesheng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!