Skip to content

Commit 63ba3af

Browse files
committed
mouredev#10 Python and Go
1 parent eec3849 commit 63ba3af

File tree

2 files changed

+224
-0
lines changed

2 files changed

+224
-0
lines changed
+123
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
package main
2+
3+
import "fmt"
4+
5+
/*
6+
* EJERCICIO:
7+
* Explora el concepto de manejo de excepciones según tu lenguaje.
8+
* Fuerza un error en tu código, captura el error, imprime dicho error
9+
* y evita que el programa se detenga de manera inesperada.
10+
* Prueba a dividir "10/0" o acceder a un índice no existente
11+
* de un listado para intentar provocar un error.
12+
*/
13+
14+
func DivInteger(a, b int) (div_ab float32, err error) {
15+
16+
defer func() {
17+
18+
r := recover()
19+
if r != nil {
20+
err = fmt.Errorf("Error como P^$!a : %v ", r)
21+
div_ab = 0
22+
}
23+
}()
24+
25+
div_ab = float32(a) / float32(b)
26+
if b == 0 {
27+
panic("B == 0")
28+
}
29+
return div_ab, nil
30+
}
31+
func sliceOutofRange(lista []int, index int) (num int, err error) {
32+
defer func() {
33+
r := recover()
34+
if r != nil {
35+
err = fmt.Errorf("Eeeeerrror %v", r)
36+
num = -1
37+
}
38+
}()
39+
num = lista[index]
40+
return num, nil
41+
42+
}
43+
44+
/* DIFICULTAD EXTRA (opcional):
45+
* Crea una función que sea capaz de procesar parámetros, pero que también
46+
* pueda lanzar 3 tipos diferentes de excepciones (una de ellas tiene que
47+
* corresponderse con un tipo de excepción creada por nosotros de manera
48+
* personalizada, y debe ser lanzada de manera manual) en caso de error.
49+
* - Captura todas las excepciones desde el lugar donde llamas a la función.
50+
* - Imprime el tipo de error.
51+
* - Imprime si no se ha producido ningún error.
52+
* - Imprime que la ejecución ha finalizado.
53+
*/
54+
55+
func CustomError(Index int, list []int) (prom float32, err error) {
56+
57+
defer func() {
58+
r := recover()
59+
if r != nil {
60+
err = fmt.Errorf("error.. %v", r)
61+
}
62+
}()
63+
Longitud := len(list)
64+
// verifico que el index este entre 0 y max longitud de la cadena
65+
if (Longitud < Index) || (Index < 0) {
66+
67+
panic(" Acceso a valores fuera de rango")
68+
}
69+
70+
if list[Longitud-1] == 10 {
71+
panic(" el ultimo elemento no puede ser 10")
72+
}
73+
74+
prom = float32(list[Longitud-1]) / float32(list[0])
75+
76+
// controlo la division por cero
77+
if float32(list[0]) == 0 {
78+
79+
panic("Division por cero no permitida")
80+
81+
}
82+
return prom, nil
83+
84+
}
85+
86+
func main() {
87+
fmt.Println("Reto #10 Exception")
88+
var a, b int
89+
90+
fmt.Print("Numerador :")
91+
fmt.Scanln(&a)
92+
fmt.Print("Denominador :")
93+
fmt.Scanln(&b)
94+
div_ab, ok := DivInteger(a, b)
95+
if ok == nil {
96+
fmt.Println("No hay error")
97+
fmt.Printf(" %v / %v = %v\n", a, b, div_ab)
98+
} else {
99+
fmt.Printf("Error div x 0 is a chaos... %v\n", ok)
100+
}
101+
102+
index := 10
103+
num, e := sliceOutofRange([]int{0, 1, 2, 3}, index)
104+
if e != nil {
105+
fmt.Printf("Error %v\n", e)
106+
} else {
107+
fmt.Printf("in %v position is %v\n", index, num)
108+
}
109+
110+
fmt.Println("EXTRA")
111+
fmt.Println()
112+
113+
prom, er := CustomError(3, []int{20, 2, 3, 4, 1, 1, 1, 100})
114+
if er != nil {
115+
fmt.Println(er)
116+
} else {
117+
fmt.Println("No se ha producido ningun error")
118+
fmt.Println("Promedio es: ", prom)
119+
}
120+
121+
fmt.Println("El programam ha finalizado")
122+
123+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# /*
2+
# * EJERCICIO:
3+
# * Explora el concepto de manejo de excepciones según tu lenguaje.
4+
# * Fuerza un error en tu código, captura el error, imprime dicho error
5+
# * y evita que el programa se detenga de manera inesperada.
6+
# * Prueba a dividir "10/0" o acceder a un índice no existente
7+
# * de un listado para intentar provocar un error.
8+
# *
9+
10+
11+
def Div_by_0(a,b):
12+
try :
13+
result = a/b
14+
15+
except ZeroDivisionError as err:
16+
print("Error Div por 0 no permitida: ", err)
17+
else:
18+
print(f" {a} / {b} = {result}")
19+
20+
finally:
21+
print("terminada la divicion")
22+
23+
def Array_out_of_range(lista, index ):
24+
try:
25+
a= lista[index]
26+
except IndexError as err:
27+
print("Error : ", err)
28+
else:
29+
print(f"{a} is in {index} position")
30+
finally:
31+
print("Se acabo la jugada")
32+
33+
34+
a = 2
35+
b = 10
36+
Div_by_0(a,b)
37+
lista = [1,2,3,4,5]
38+
index = 11
39+
Array_out_of_range(lista, index)
40+
41+
# * DIFICULTAD EXTRA (opcional):
42+
# * Crea una función que sea capaz de procesar parámetros, pero que también
43+
# * pueda lanzar 3 tipos diferentes de excepciones (una de ellas tiene que
44+
# * corresponderse con un tipo de excepción creada por nosotros de manera
45+
# * personalizada, y debe ser lanzada de manera manual) en caso de error.
46+
# * - Captura todas las excepciones desde el lugar donde llamas a la función.
47+
# * - Imprime el tipo de error.
48+
# * - Imprime si no se ha producido ningún error.
49+
# * - Imprime que la ejecución ha finalizado.
50+
# */
51+
52+
class customError( Exception):
53+
pass
54+
55+
def custom_error():
56+
while True:
57+
print("Que error quieres ver :")
58+
print()
59+
print("1 - Division por Zero")
60+
print("2 - Index fuera de rango")
61+
print("3 - Personalizado ")
62+
print("4 - Salir")
63+
print()
64+
op = input()
65+
match op:
66+
case "1":
67+
raise ZeroDivisionError()
68+
case "2":
69+
raise IndexError()
70+
case "3":
71+
print("que error quieres mostrar")
72+
a = input()
73+
raise customError(a)
74+
case "4":
75+
break
76+
case _:
77+
print("OPcion invalida...")
78+
79+
80+
81+
82+
83+
84+
try:
85+
86+
custom_error()
87+
88+
except ZeroDivisionError as e:
89+
print(f"**** Error 1 ***** : Division por zero")
90+
except IndexError as e:
91+
print(f"**** Error 2 ***** : error de index")
92+
except customError as e:
93+
print(f"**** Error 3 ***** : {e}")
94+
except Exception as e:
95+
print(f"**** Error Inesperado ***** : {e}")
96+
else:
97+
print("No Error ")
98+
finally:
99+
print("Done...")
100+
101+

0 commit comments

Comments
 (0)