GOLANG

Error handling in Go

Go does not provide conventional try/catch method to handle the errors, instead, errors are returned as a normal return value. In this article, we are going to explore error handling in Go.

Uday Hiwarale
RunGo
Published in
13 min readJun 12, 2019

--

(source: pexels.com)

Conventionally, we learned an error is something that is fatal to the program but in Go, error has a different meaning. An error is just a value that a function can return if something unexpected happened.

So what could happen in a function that is unexpected? For example, the function was invoked with wrong arguments or execution inside the function did not go as expected. In that case, this function can return an error as a value.

error is a built-in type in Go and its zero value is nil. An idiomatic way to handle an error is to return it as the last return value of a function call and check for the nil condition.

val, err := myFunction( args... );if err != nil {
// handle error
} else {
// success
}

If you are familiar with the Node.js, then any async function callback returns an error as the first argument. In Go, we follow the same norm.

--

--