Skip to content

Commit d54a72b

Browse files
committed
1 parent 32a7815 commit d54a72b

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"errors"
6+
)
7+
8+
func main() {
9+
10+
// Dividir 10/0
11+
_, err := divide(10, 0)
12+
if err != nil {
13+
fmt.Println("Error al dividir: ", err)
14+
}
15+
16+
// Acceder a un índice no existente de un listado
17+
list := []int{1, 2, 3}
18+
_, err = iterateList(list)
19+
if err != nil {
20+
fmt.Println("Error al iterar: ", err)
21+
}
22+
23+
// Extra: Procesar parámetros
24+
value1, err := process(10, 2)
25+
if err != nil {
26+
fmt.Println("Error al procesar parámetros: ", err)
27+
} else {
28+
fmt.Println("Parametros procesados correctamente: ", value1)
29+
}
30+
31+
value2, err := process(13, 2)
32+
if err != nil {
33+
fmt.Println("Error al procesar parámetros: ", err)
34+
} else {
35+
fmt.Println("El resultado es: ", value2)
36+
}
37+
38+
fmt.Println("El programa continua, no termina inesperadamente al haber errores ya que los estamos manejando...")
39+
}
40+
41+
func divide(a, b int) (int, error) {
42+
if b == 0 {
43+
return 0, errors.New("No se puede dividir por 0")
44+
}
45+
return a / b, nil
46+
}
47+
48+
func iterateList(list []int) (int, error) {
49+
for i := 0; i < len(list)+1; i++ {
50+
if i >= len(list) {
51+
return 0, errors.New("Indice fuera de rango")
52+
}
53+
fmt.Println(list[i])
54+
}
55+
return 0, nil
56+
}
57+
58+
// Extra:
59+
60+
type MyError struct {
61+
code int
62+
msg string
63+
}
64+
65+
func (e *MyError) Error() string {
66+
return fmt.Sprintf("Error %d: %s", e.code, e.msg)
67+
}
68+
69+
func process(a, b int) (int, error) {
70+
if a <= 0 {
71+
return 0, errors.New("El primer parámetro no puede ser negativo ni 0")
72+
}
73+
if b <= 0 {
74+
return 0, errors.New("El segundo parámetro no puede ser negativo ni 0")
75+
}
76+
if a == 13 {
77+
return 0, &MyError{code: 13, msg: "El primer parámetro no puede ser 13"}
78+
}
79+
if b == 13 {
80+
return 0, &MyError{code: 13, msg: "El segundo parámetro no puede ser 13"}
81+
}
82+
fmt.Println("Ejecucion finalizada sin errores.")
83+
return a + b, nil
84+
}

0 commit comments

Comments
 (0)