Manejo de errores
Los errores van a pasar sí o sí: un dato mal escrito, una red que falla. La diferencia la hace qué pasa cuando ocurren.
Error handling
Errors will happen, guaranteed: bad input, a network that fails. What makes the difference is what happens when they do.
Cuando JavaScript encuentra un error que nadie maneja, el script se detiene ahí mismo. Todo lo que venía después de esa línea no se ejecuta nunca.
When JavaScript hits an error nobody handles, the script stops right there. Everything after that line never runs.
try envuelve el código que podría fallar. Si algo dentro explota,
catch lo atrapa —con el error como argumento— y el programa sigue
vivo en vez de morir ahí.
try wraps code that might fail. If something inside blows up,
catch catches it — with the error as its argument — and the program
stays alive instead of dying there.
No todos los errores vienen del navegador. Con throw puedes lanzar uno tú
mismo cuando tu propia lógica detecta que algo no tiene sentido —por ejemplo, un dato que
nunca debería ser negativo—.
Not every error comes from the browser. With throw you can raise one
yourself, when your own logic detects something that makes no sense — for example, a value
that should never be negative.
La primera llamada funciona bien. La segunda entra al
if, hace throw, y ese error viaja hasta el catch más
cercano —da igual cuántas funciones haya en el medio—.
The first call works fine. The second one enters the
if, does throw, and that error travels up to the nearest
catch — no matter how many functions sit in between.
finally se ejecuta siempre, haya fallado algo o no. Sirve para cosas que
tienen que pasar de todas formas —como ocultar un mensaje de "cargando"—.
finally always runs, whether something failed or not. It is for things that
need to happen either way — like hiding a "loading" message.
try/catch para que un error no rompa todo el programa,
throw para lanzar tus propios errores, y finally para lo que debe
pasar sí o sí.
Con esto tus programas pueden fallar sin morir. Ya tienes todas las piezas del lenguaje: lo que sigue es usarlas para cosas más grandes.
try/catch so an error does not break the whole program,
throw to raise your own errors, and finally for what must happen no
matter what.
With this your programs can fail without dying. You now have every piece of the language: what is left is using them for bigger things.