Skip to content

Commit 6a6d65a

Browse files
author
Amador Quispe
committed
1 parent 214e371 commit 6a6d65a

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package main
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"strconv"
7+
)
8+
9+
//De manera general, GO representa cualquier tipo de error mediante la interfaz error:
10+
11+
func main() {
12+
//División por cero
13+
if res, err := divideTwoNumbers(10, 0); err == nil {
14+
fmt.Println(res)
15+
} else {
16+
fmt.Println(err)
17+
}
18+
19+
//Indice fuera de rango
20+
numbers := []int{1, 2, 3, 4, 5, 6}
21+
val, err := getElementByIndex(numbers, 6)
22+
if err != nil {
23+
fmt.Println(err)
24+
} else {
25+
fmt.Println(val)
26+
27+
}
28+
29+
//Error personalizado
30+
result, err := divisionPositive(-34, 3)
31+
if err != nil {
32+
fmt.Println(err)
33+
} else {
34+
fmt.Println(result)
35+
}
36+
}
37+
38+
func divideTwoNumbers(a, b int) (int, error) {
39+
if b == 0 {
40+
return 0, errors.New("cannot divide by zero")
41+
}
42+
return a / b, nil
43+
}
44+
45+
func getElementByIndex[T any](slice []T, i int) (T, error) {
46+
if len(slice) >= i {
47+
var zeroValue T
48+
return zeroValue, errors.New("index of range! it must be less than " + strconv.Itoa(i))
49+
}
50+
return slice[i], nil
51+
}
52+
53+
type CustomError struct {
54+
msg string
55+
}
56+
57+
func (ce *CustomError) Error() string {
58+
return ce.msg
59+
}
60+
61+
func divisionPositive(numerator, denominator int) (int, error) {
62+
if numerator < 0 || denominator < 0 {
63+
return 0, &CustomError{msg: "not valid numbers negatives"}
64+
}
65+
return numerator / denominator, nil
66+
}

0 commit comments

Comments
 (0)