try.. catch… throw… Ejemplo

Os dejamos un ejemplo Javascript para las sentencias try, catch y throw que manipulan el manejo de errores. Su sintaxis es la siguiente:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Try.. catch... finally - Personalizar nuestros mensajes</title>
  </head>

  <body>
    <h1>Try.. catch... finally - Personalizar nuestros mensajes</h1>

    <script>
      try {
        let numero = 10;
        if (isNaN(numero)) {
          throw new Error("El caracter introducido no es un número");
        }
        console.log(numero * numero);
      } catch (error) {
        console.log("Se produjo el siguiente error: " + error);
      }
    </script>
  </body>
</html>
Scroll al inicio