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:
- If
jumlah <= 0→ returnsaldo(unchanged) and the error"jumlah penarikan harus lebih dari nol"("withdrawal amount must be greater than zero"). - If
jumlah > saldo→ returnsaldo(unchanged) and the error"saldo tidak cukup"("insufficient balance"). - Otherwise → return
saldo - jumlahandnil.
Use errors.New to create the errors, and don't forget to add the "errors" package to the import section.