1+ /*
2+ Clase 6 en vídeo | 15/08/2024
3+ Clases (continuación) y manejo de errores
4+ https://www.twitch.tv/videos/2225058195?t=00h16m42s
5+ */
6+
7+ // Excepción
8+
9+ // Produce una excepción
10+ let myObject
11+ // console.log(myObject.email)
12+
13+ // Captura de errores
14+
15+ // try-catch
16+
17+ try {
18+ // Código que intenta ejecutar
19+ console . log ( myObject . email )
20+ console . log ( "Finaliza la ejecución sin errores" )
21+ } catch {
22+ // Bloque de error
23+ console . log ( "Se ha producido un error" )
24+ }
25+
26+ // Captura del error
27+
28+ try {
29+ console . log ( myObject . email )
30+ } catch ( error ) {
31+ console . log ( "Se ha producido un error:" , error . message )
32+ }
33+
34+ // finally
35+
36+ try {
37+ console . log ( myObject . email )
38+ } catch ( error ) {
39+ console . log ( "Se ha producido un error:" , error . message )
40+ } finally {
41+ console . log ( "Este código se ejecuta siempre" )
42+ }
43+
44+ // No está soportado
45+ // try {
46+ // console.log(myObject.email)
47+ // } finally {
48+ // console.log("Este código se ejecuta siempre")
49+ // }
50+
51+ // Lanzamiento de errores
52+
53+ // throw
54+
55+ // throw new Error("Se ha producido un error");
56+
57+ function sumIntegers ( a , b ) {
58+ if ( typeof a !== "number" || typeof b !== "number" ) {
59+ throw new TypeError ( "Esta operación sólo suma números" )
60+ }
61+ if ( ! Number . isInteger ( a ) || ! Number . isInteger ( b ) ) {
62+ throw new Error ( "Esta operación sólo suma números enteros" )
63+ }
64+ if ( a == 0 || b == 0 ) {
65+ throw new SumZeroIntegerError ( "Se está intentando sumar cero" , a , b )
66+ }
67+ return a + b
68+ }
69+
70+ try {
71+ console . log ( sumIntegers ( 5 , 10 ) )
72+ // console.log(sumIntegers(5.5, 10))
73+ console . log ( sumIntegers ( "5" , 10 ) )
74+ // console.log(sumIntegers(5, "10"))
75+ // console.log(sumIntegers("5", "10"))
76+ } catch ( error ) {
77+ console . log ( "Se ha producido un error:" , error . message )
78+ }
79+
80+ // Capturar varios tipos de errores
81+
82+ try {
83+ // console.log(sumIntegers(5.5, 10))
84+ console . log ( sumIntegers ( "5" , 10 ) )
85+ } catch ( error ) {
86+ if ( error instanceof TypeError ) {
87+ console . log ( "Se ha producido un error de tipo:" , error . message )
88+ } else if ( error instanceof Error ) {
89+ console . log ( "Se ha producido un error:" , error . message )
90+ }
91+ }
92+
93+ // Crear excepciones personalizadas
94+
95+ class SumZeroIntegerError extends Error {
96+ constructor ( message , a , b ) {
97+ super ( message )
98+ this . a = a
99+ this . b = b
100+ }
101+
102+ printNumbers ( ) {
103+ console . log ( this . a , " + " , this . b )
104+ }
105+ }
106+
107+ try {
108+ console . log ( sumIntegers ( 0 , 10 ) )
109+ } catch ( error ) {
110+ console . log ( "Se ha producido un error personalizado:" , error . message )
111+ error . printNumbers ( )
112+ }
0 commit comments