Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

The throw Statement

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 stringnumberboolean, 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.

Input Validation Example

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 < 5throw “too low”;
    if(x > 10throw “too high”;
  }
  catch(err) {
    message.innerHTML = “Input is “ + err;
  }
}
</script>

</body>
</html>

HTML Validation

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

The finally statement allows you to execute code after the try and catch blocks, regardless of the outcome.

Syntax

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
}

Example

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 > 10throw “is too high”;
    if(x < 5throw “is too low”;
  }
  catch(err) {
    message.innerHTML = “Error: “ + err + “.”;
  }
  finally {
    document.getElementById(“demo”).value = “”;
  }
}