forked from mouredev/hello-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path25-error-handling-exercises.js
More file actions
116 lines (105 loc) · 2.45 KB
/
25-error-handling-exercises.js
File metadata and controls
116 lines (105 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
Clase 41 - Ejercicios: Manejo de errores
Vídeo: https://youtu.be/1glVfFxj8a4?t=20392
*/
// 1. Captura una excepción utilizando try-catch
try {
throw new Error("This is an error")
} catch (error) {
console.log(error)
}
// 2. Captura una excepción utilizando try-catch y finally
try {
throw new Error("This is an error")
}
catch (error) {
console.log(error)
}
finally {
console.log("This is the finally block")
}
// 3. Lanza una excepción genérica
try {
throw new Error("This is an error")
} catch (error) {
console.log(error)
}
// 4. Crea una excepción personalizada
class MyError extends Error {
constructor(message) {
super(message)
this.name = "MyError"
}
}
try {
throw new MyError("This is a custom error")
}
catch (error) {
console.log(error)
}
// 5. Lanza una excepción personalizada
try {
throw new MyError("This is a custom error")
} catch (error) {
console.log(error)
}
// 6. Lanza varias excepciones según una lógica definida
function checkNumber(number) {
if (number < 0) {
throw new Error("The number is negative")
}
if (number === 0) {
throw new Error("The number is zero")
}
if (number > 0) {
throw new Error("The number is positive")
}
}
checkNumber(5)
checkNumber(0)
checkNumber(-5)
// 7. Captura varias excepciones en un mismo try-catch
try {
checkNumber(5)
checkNumber(0)
checkNumber(-5)
} catch (error) {
console.log(error)
}
// 8. Crea un bucle que intente transformar a float cada valor y capture y muestre los errores
let values = [1, 2, 3, "four", 5]
for (let value of values) {
try {
console.log(parseFloat(value))
} catch (error) {
console.log(error)
}
}
// 9. Crea una función que verifique si un objeto tiene una propiedad específica y lance una excepción personalizada
function checkProperty(object, property) {
if (!object.hasOwnProperty(property)) {
throw new Error("The property does not exist")
}
}
let myObject = {
name: "Fernando",
age: 37
}
try {
checkProperty(myObject, "country")
} catch (error) {
console.log(error)
}
// 10. Crea una función que realice reintentos en caso de error hasta un máximo de 10
function retryOperation() {
let retries = 0
while (retries < 10) {
try {
throw new Error("This is an error")
} catch (error) {
console.log(error)
retries++
}
}
}
retryOperation()