Go course

ErrorsThe error Interface

Go

Display

Theme

Errors · Test exercise

The error Interface

Go has no exceptions. A failure is treated as an ordinary value that a function returns. The type of that value is the built-in error interface:

type error interface {
	Error() string
}

That's right, error is just a tiny interface with a single method! Anything that has an Error() string method is an error.

Returning an error

The convention: a function that can fail returns an error as its last value. If it succeeds, the error is nil.

import "errors"

func bagi(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("tidak bisa membagi dengan nol")
	}
	return a / b, nil
}

errors.New creates a simple error holding a text message (here, "cannot divide by zero").

Checking an error

The caller always checks the error before using the result:

hasil, err := bagi(10, 0)
if err != nil {
	fmt.Println("Gagal:", err)   // Gagal: tidak bisa membagi dengan nol
	return
}
fmt.Println("Hasil:", hasil)

You'll see the if err != nil { ... } pattern all the time in Go code. When an error occurs, the other returned values are usually zero values and shouldn't be trusted.

Go's tradition for error messages: start with a lowercase letter and no period at the end, because error messages are often joined with other messages.

Task

A digital wallet needs a function for withdrawing from a balance. Complete:

func tarikSaldo(saldo, jumlah int) (int, error)

The rules, checked in order:

  1. If jumlah <= 0 → return saldo (unchanged) and the error "jumlah penarikan harus lebih dari nol" ("withdrawal amount must be greater than zero").
  2. If jumlah > saldo → return saldo (unchanged) and the error "saldo tidak cukup" ("insufficient balance").
  3. Otherwise → return saldo - jumlah and nil.

Use errors.New to create the errors, and don't forget to add the "errors" package to the import section.

main.go
package main

import "fmt"

// TODO: tambahkan paket "errors" ke import saat Anda memakai errors.New

func tarikSaldo(saldo, jumlah int) (int, error) {
	// TODO: validasi jumlah dan saldo, kembalikan error dengan errors.New
	return saldo - jumlah, nil
}

func main() {
	sisa, err := tarikSaldo(100000, 250000)
	if err != nil {
		fmt.Println("Gagal:", err)
		return
	}
	fmt.Println("Sisa saldo:", sisa)
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)