Go Notebook
  • Introduction
  • Syntax Helpers
    • Append
    • String
    • Slice
  • Idioms
    • Custom JSON Marshaling
    • Functional Options
    • Type Embedding
    • Laws of Reflection
  • Design Patterns
    • Builder
    • Factory Method
    • Object Pool
    • Singleton
    • Observer
    • Strategy
  • Hello World
    • Getting Started With Go
    • Go Packages
    • Hello World
  • Tic Tac Toe
    • Go Interfaces
    • Go Error Handling
    • Tic Tac Toe
  • HTTP Server
    • HTTP Handler
    • Build a Calculator
    • HTTP Unit Test
  • Concurrency
    • Goroutines
    • Go Concurrency Part 1
    • Go Concurrency Part 2
  • WebSocket Server
    • WebSocket Handler
    • Build a Chatroom
  • User Authentication
    • Go Module
    • Popular Web Libraries
    • React Tools
    • Build an Authentication Server
  • Numerical Computing
    • Gonum
    • Neural Networks
Powered by GitBook
On this page
  1. Tic Tac Toe

Go Error Handling

Error handling is a must for any program. The common approach in JavaScript, Python and Java is using try catch statement to handle exceptions, but we don't have exceptions in Go! For example, let's say we are trying to feed Eric Cartman with unhealthy food.

In Python, we would do the following.

def feed(kid, food):
  if food.calorie > 1000:
    raise ValueError("this will kill your kid")

  kid.eat(food)


def main():
  # Initialize the objects...
  try:
    feed(eric, french_fries)
  except ValueError:
    print "please don't do that, he's fat, not big bone"

In Go, we would simply return an error.

func feed(k *Kid, f *Food) error {
  if food.calorie > 1000 {
    return errors.New("this will kill your kid")
  }

  k.eat(f)
  return nil
}

func main() {
  // Initialize the objects...
  if err := feed(eric, frenchFries); err != nil {
    fmt.Println("please don't do that, he's fat, not big bone")
    log.Error(err) // Log the error
  }
}
PreviousGo InterfacesNextTic Tac Toe

Last updated 6 years ago