Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Throw new exception in Go

Exceptions are little different in Go compared to other languages like Java, C# and Python. And the concept of handling is also different. In this example we can see how to create an exception with error message and how it is handled inside calling function. A typical if condition is necessary to check whether the method resulted in an error.

package main

import (
    "errors"
    "fmt"
)

func main() {
    var car = Car{}
    car.name = "Audi"

    var output, error = car.getMileage()

    if error != nil {
        fmt.Printf("Error is received %+v", error)
        return
    }

    print(output)
}

type Car struct {
    name string
}

func (car Car) getMileage() (int, error) {
    return -1, errors.New("unable to compute mileage")
}



Output
Error is received unable to compute mileage