1
+ #10 { Retos para Programadores } EXCEPCIONES
2
+
3
+ # Bibliography reference
4
+ #Python Notes for Professionals. 800+ pages of professional hints and tricks (GoalKicker.com) (Z-Library)
5
+ # GPT
6
+
7
+
8
+ """
9
+ * EJERCICIO:
10
+ * Explora el concepto de manejo de excepciones según tu lenguaje.
11
+ * Fuerza un error en tu código, captura el error, imprime dicho error
12
+ * y evita que el programa se detenga de manera inesperada.
13
+ * Prueba a dividir "10/0" o acceder a un índice no existente
14
+ * de un listado para intentar provocar un error.
15
+ *
16
+ * DIFICULTAD EXTRA (opcional):
17
+ * Crea una función que sea capaz de procesar parámetros, pero que también
18
+ * pueda lanzar 3 tipos diferentes de excepciones (una de ellas tiene que
19
+ * corresponderse con un tipo de excepción creada por nosotros de manera
20
+ * personalizada, y debe ser lanzada de manera manual) en caso de error.
21
+ * - Captura todas las excepciones desde el lugar donde llamas a la función.
22
+ * - Imprime el tipo de error.
23
+ * - Imprime si no se ha producido ningún error.
24
+ * - Imprime que la ejecución ha finalizado.
25
+
26
+ """
27
+
28
+ log = print
29
+
30
+ import time
31
+
32
+ # Short for print()
33
+ log = print
34
+
35
+ # Simulating window load event
36
+ def on_load ():
37
+ body_style = {
38
+ 'background' : '#000' ,
39
+ 'text-align' : 'center'
40
+ }
41
+
42
+ title = 'Retosparaprogramadores #10.'
43
+ title_style = {
44
+ 'font-size' : '3.5vmax' ,
45
+ 'color' : '#fff' ,
46
+ 'line-height' : '100vh'
47
+ }
48
+
49
+ # Simulating setting styles and appending title to body
50
+ log (f"Body style: { body_style } " )
51
+ log (f"Title: { title } with style: { title_style } " )
52
+
53
+ time .sleep (2 ) # Simulating delay
54
+ log ('Retosparaprogramadores #10.' )
55
+
56
+ on_load ()
57
+
58
+ # Runtime errors in Python are instances of the Exception class.
59
+ # The Exception class can also be used as-is, or as the base for user-defined exceptions.
60
+ # It's possible to raise any type of value - for example, strings - but you're strongly encouraged to use Exception or one of its derivatives.
61
+
62
+ num = 0
63
+ result = None
64
+
65
+ try :
66
+ if isinstance (num , (int , float )) and num != 0 :
67
+ result = 10 / num
68
+ elif num == 0 :
69
+ raise ValueError ("It seems you've tried to divide by zero, which is not permitted. Please enter a valid non-zero number." )
70
+ else :
71
+ raise TypeError ("It seems you've tried to divide by a non-number value, which is not permitted. Please enter a valid number." )
72
+ except Exception as error :
73
+ log ('Something went wrong! ' + str (error ))
74
+
75
+ log (result ) # Something went wrong! It seems you've tried to divide by zero, which is not permitted. Please enter a valid non-zero number. & None
76
+
77
+ # Note: Python raises ZeroDivisionError for division by zero, but we explicitly raise a ValueError to inform about it.
78
+
79
+ # Example of handling exceptions in a promise-like manner using a function
80
+ def promise_example ():
81
+ try :
82
+ result = 102
83
+ raise Exception ("explicitly rejected promise" )
84
+ except Exception as error :
85
+ log ("Promise rejected: " + str (error ))
86
+
87
+ promise_example () # Promise rejected: explicitly rejected promise
88
+
89
+ # There are several specific core error types in Python:
90
+ # ValueError - raised when a function receives an argument of the right type but inappropriate value.
91
+ # TypeError - raised when an operation or function is applied to an object of inappropriate type.
92
+ # KeyError - raised when a dictionary key is not found.
93
+ # IndexError - raised when a sequence subscript is out of range.
94
+ # SyntaxError - raised when the parser encounters a syntax error.
95
+ # AttributeError - raised when an invalid attribute reference is made.
96
+
97
+ def get_user_name (user ):
98
+ try :
99
+ name = user ['name' ].upper ()
100
+ log (f"User name: { name } " )
101
+ except KeyError :
102
+ log ('KeyError: Cannot read property "name" of undefined or null' )
103
+ except Exception as e :
104
+ log ('Instance of general Exception: ' + str (e ))
105
+
106
+ get_user_name ({'name' : 'Roxy' }) # User name: Roxy
107
+ get_user_name ({}) # KeyError: Cannot read property "name" of undefined or null
108
+
109
+ # Extra exercises
110
+ def check_values (arr , index ):
111
+ try :
112
+ if not isinstance (arr , list ):
113
+ raise TypeError ('The first parameter must be of type list.' )
114
+ elif len (arr ) == 0 :
115
+ raise ValueError ('You provided an empty array as a parameter!' )
116
+
117
+ if index >= len (arr ) or index < 0 :
118
+ raise IndexError (f"{ index } is not a valid index for the array given." )
119
+
120
+ log (f"The position given corresponds to this value: { arr [index ]} " )
121
+ log ("There's no errors when executing the function." )
122
+
123
+ except Exception as e :
124
+ log (f"{ type (e ).__name__ } : Ooops! { e } " )
125
+ finally :
126
+ log ('The process is finished' )
127
+
128
+ check_values ([8 , 5 , 6 , 4 ], 8 ) # IndexError: Ooops! 8 is not a valid index for the array given & The process is finished
129
+ check_values ([], 4 ) # ValueError: Ooops! You provided an empty array as a parameter! & The process is finished
130
+ check_values ([0 , 76 , 32 , 1 , 4 , 2 ], 'Kia' ) # TypeError: Ooops! The first parameter must be of type list. & The process is finished
131
+ check_values ([4 , 5 , 3 , 18 , 22 ], 3 ) # The position given corresponds to this value: 18
132
+ # There's no errors when executing the function.
133
+ # The process is finished
0 commit comments