Unlike in other languages, there is no try...catch
block in Go. In this section, we're going to see how Go handles basic errors. So, the first thing we're going to see is how to handle the errors returned by an API calls. We can use the time.Parse()
method for that as it accepts a layout and a value string. It returns two things, one is the parsedDate
and the other one is an error. Instead of returning an exception, Go returns an error as its second parameter most of the time.
Now, the way you can handle this is to check whether the parsedDate
is nil. If it's not nil in Go, then we know that an error has happened and we need to handle it. If nothing happens, we can safely proceed to our next line, and that is to write the content of our parsedDate
to output. So, for this, check the following code example:
package main import ( "time" "fmt" ) func main(){ parsedDate, err:= time.Parse("2006", "2018") if err != nil { fmt.Println("An error occured...