Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang :how do I handle index out of range error?

Tags:

go

panic

I am writing a CLI interface program in Go.my program requires a user to enter a filename as an argument . following is the code I wrote to handle the situations in which user doesn't enter any argument . but it panics and gives an error "index out of range".how do I handle this?

  package main

import (
    "encoding/hex"
    "fmt"
    "io/ioutil"
    "log"
    "os"
)

func main() {
    if len(os.Args) == 0 {
        fmt.Println("usage: gohex  <filename>")

        os.Exit(1)
    } else {
        filename := os.Args[1]

        data, err := ioutil.ReadFile(filename)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(hex.Dump(data))
    }

}
like image 544
Prithviraj Sukale Avatar asked May 12 '16 18:05

Prithviraj Sukale


2 Answers

Your problem relies in this line:

if len(os.Args) == 0

You are checking for the first argument which as you supposed should be the filename, but in fact is the go / executable filename. So if you wish to check if an argument has been provided you need to check that the argument length is greater than 1. Change the code to:

if len(os.Args) <= 1 {
    log.Fatal("usage: gohex  <filename>")
}
like image 69
Endre Simo Avatar answered Oct 21 '22 00:10

Endre Simo


The other answer has a couple of issues. It has this check:

len(os.Args) <= 1

but len(os.Args) must always be at least 1, so using <= is pointless. Further, in this specific case, len of anything other than 2 is invalid as well. So just check that:

package main
import "os"

func main() {
   if len(os.Args) != 2 {
      println("gohex <filename>")
      return
   }
   filename := os.Args[1]
   println(filename)
}

Side note, personally I also think using os.Exit(1) is invalid in this context as well. I think "printing the help text" is a valid use case, and not an error.

like image 36
Zombo Avatar answered Oct 21 '22 00:10

Zombo