Skip to content
Exercise · Errors · lesson 11 of 11

Exercise: division with an error

The starter code already declares the sentinel error var ErrDivByZero = errors.New("division by zero"). Write a function func divide(a, b int) (int, error) that returns the quotient a / b and nil. If b is zero, the function returns 0 and an error that wraps ErrDivByZero with %w and has the text divide <a>: division by zero.

  • divide(7, 2) → 3, nil
  • divide(7, 0) → 0 and an error with the text divide 7: division by zero, for which errors.Is(err, ErrDivByZero) is true
  • divide(-4, 0) → 0 and an error with the text divide -4: division by zero

Constraints: a and b are from -1000 to 1000 and may be negative or zero.

Do not add extra imports unless the task says so explicitly.

divide.go — go
go · 10 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way