Skip to content

Commit 8cabfd6

Browse files
fix(26_errors): implement divide and processDivision with error handling (#87)
1 parent 5632411 commit 8cabfd6

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

  • internal/exercises/solutions/26_errors
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package errors
2+
3+
import (
4+
"fmt"
5+
"os"
6+
)
7+
8+
// divZeroErr is a minimal error type whose message is "division by zero".
9+
type divZeroErr struct{}
10+
11+
// Error makes divZeroErr implement error.
12+
func (divZeroErr) Error() string { return "division by zero" }
13+
14+
// Is allows errors.Is(err, errors.New("division by zero")) to succeed.
15+
func (divZeroErr) Is(target error) bool {
16+
if target == nil {
17+
return false
18+
}
19+
return target.Error() == "division by zero"
20+
}
21+
22+
// divide returns a/b or a "division by zero" error when b == 0.
23+
func divide(a, b int) (int, error) {
24+
if b == 0 {
25+
return 0, divZeroErr{}
26+
}
27+
return a / b, nil
28+
}
29+
30+
// processDivision prints the result or the error to stdout.
31+
func processDivision(a, b int) {
32+
res, err := divide(a, b)
33+
if err != nil {
34+
fmt.Fprint(os.Stdout, "Error: ", err, "\n")
35+
return
36+
}
37+
fmt.Fprint(os.Stdout, "Result: ", res, "\n")
38+
}

0 commit comments

Comments
 (0)