JavaScript · JS Tutorial · Lesson 36
JS Errors
try, catch, finally and throw.
The try statement defines a block of code to run (to try). catch handles errors, finally always runs, and throw creates custom errors.
Example
<input id="num" type="number" placeholder="Number 5-10"> <button onclick="check()">Test</button>
<p id="demo"></p>
<script>
function check() {
const msg = document.getElementById("demo");
const x = document.getElementById("num").value;
try {
if (x.trim() === "") throw "is empty";
if (isNaN(x)) throw "is not a number";
if (Number(x) < 5) throw "is too low";
if (Number(x) > 10) throw "is too high";
msg.innerHTML = "Input is OK";
} catch (err) {
msg.innerHTML = "Input " + err;
} finally {
document.getElementById("num").value = "";
}
}
</script>
| Error name | Cause |
|---|---|
| ReferenceError | Using a variable that is not declared |
| SyntaxError | Invalid code |
| TypeError | A value is not of the expected type |
| RangeError | A number is out of range |
Keep reading “JS Errors”
Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.