The throw statement enables you to create a custom error.
Technically, you can throw an exception (throw an error).
The exception can be a JavaScript string, number, boolean, or object.
throw “Too big”; // throw a text throw 500; // throw a number |
By using throw along with try and catch, you can control the program’s flow and create custom error messages.
This example checks the input. If the value is incorrect, an exception (err
) is thrown.
The catch
statement catches the exception (err
) and displays a custom error message.
<!DOCTYPE html> <html> <body> <p>Please input a number between 5 and 10:</p> <input id=”demo” type=”text”> <button type=”button” onclick=”myFunction()”>Test Input</button> <p id=”p01″></p> <script> function myFunction() { const message = document.getElementById(“p01”); message.innerHTML = “”; let x = document.getElementById(“demo”).value; try { if(x.trim() == “”) throw “empty”; if(isNaN(x)) throw “not a number”; x = Number(x); if(x < 5) throw “too low”; if(x > 10) throw “too high”; } catch(err) { message.innerHTML = “Input is “ + err; } } </script> </body> </html> |
The code above is simply an example.
Modern browsers typically combine JavaScript with built-in HTML validation, utilizing predefined validation rules specified in HTML attributes.
<input id=”demo” type=”number” min=”5″ max=”10″ step=”1″> |
You can learn more about form validation in a later chapter of this tutorial.
The finally statement allows you to execute code after the try and catch blocks, regardless of the outcome.
try { Block of code to try } catch(err) { Block of code to handle errors } finally { Block of code to be executed regardless of the try / catch result } |
function myFunction() { const message = document.getElementById(“p01”); message.innerHTML = “”; let x = document.getElementById(“demo”).value; try { if(x.trim() == “”) throw “is empty”; if(isNaN(x)) throw “is not a number”; x = Number(x); if(x > 10) throw “is too high”; if(x < 5) throw “is too low”; } catch(err) { message.innerHTML = “Error: “ + err + “.”; } finally { document.getElementById(“demo”).value = “”; } } |