24. JavaScript Errors
What you will learn
- The kinds of errors you will meet
- How to read an error message
- How to handle errors with
try...catch - How to throw your own errors
- Basic debugging tips
Kinds of errors
| Error | Cause |
|---|---|
SyntaxError |
The code is written wrongly, such as a missing bracket. The script will not run at all |
ReferenceError |
Using a variable that does not exist |
TypeError |
Using a value in a way its type does not allow, such as calling something that is not a function |
RangeError |
A number outside the allowed range |
There are also logic errors: the code runs without any message but gives the wrong answer. They are often the hardest to find.
Reading an error
Press F12 and open the Console tab. Errors appear in red with a message, the file, and the line number. Start with the first error, because later ones are often caused by it.
try…catch
Put risky code in try. If it throws an error, JavaScript jumps to catch instead of stopping the script.
Example
<p id="demo"></p>
<script>
try {
const result = missingFunction(); // does not exist
document.getElementById("demo").textContent = result;
} catch (error) {
document.getElementById("demo").textContent =
"Caught: " + error.name + " - " + error.message;
}
</script>
Output (after the script runs)
Caught: ReferenceError – missingFunction is not defined
The error object has a name and a message.
finally
A finally block runs whether or not an error happened. It is good for cleanup, such as hiding a loading message.
Example
<p id="demo"></p>
<script>
let log = "";
try {
log += "Trying... ";
JSON.parse("{ not valid json }");
} catch (error) {
log += "Caught a " + error.name + ". ";
} finally {
log += "Finally always runs.";
}
document.getElementById("demo").textContent = log;
</script>
Output (after the script runs)
Trying… Caught a SyntaxError. Finally always runs.
Throwing your own errors
Use throw when something is wrong that your code should not continue past. Throw an Error object with a clear message.
Example
<p id="demo"></p>
<script>
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
let message;
try {
message = "10 / 2 = " + divide(10, 2) + " | ";
message += "10 / 0 = " + divide(10, 0);
} catch (error) {
message += "Error: " + error.message;
}
document.getElementById("demo").textContent = message;
</script>
Output (after the script runs)
10 / 2 = 5 | Error: Cannot divide by zero
Handling errors kindly
- Show visitors a friendly message, not a technical one.
- Record the technical details for yourself, for example with
console.error(error). - Catch errors where you can do something useful about them. Do not wrap everything in an empty
catch, which hides problems.
Debugging tips
- Read the message and the line number in the console.
- Print values with
console.log()to see what your variables really contain. - Use the debugger: in the browser’s Sources tab, click a line number to set a breakpoint. The code pauses there and you can inspect every variable and step line by line.
- Simplify: comment out code until the problem disappears, then bring it back piece by piece.
- Check spelling and capital letters, which cause a large share of errors.
- Explain it aloud. Describing the code line by line often reveals the mistake.
Adding "use strict"; at the top of a script makes JavaScript stricter, turning some silent mistakes (such as using an undeclared variable) into visible errors. Modules, which you will meet soon, are strict automatically.
Common mistakes
- Ignoring red messages in the console.
- An empty
catchblock that swallows errors silently. - Throwing plain strings instead of
Errorobjects. - Expecting
try...catchto catch aSyntaxErrorin the same script. The script never starts to run. - Showing raw technical messages to visitors.
Exercise
Complete getAge so it throws Error("Age must be a number") when the value is not a number, and otherwise returns the number. Call it with "abc" inside try...catch and show the message.
Show solution
<p id="demo"></p>
<script>
function getAge(value) {
const number = Number(value);
if (Number.isNaN(number)) {
throw new Error("Age must be a number");
}
return number;
}
try {
getAge("abc");
} catch (error) {
document.getElementById("demo").textContent = error.message;
}
</script>
Knowledge check
1. Which block runs only when an error is thrown?
catch
2. Which block always runs?
finally
3. Which error means a variable does not exist?
ReferenceError
Summary
- Read the console message and line number first.
- Use
try...catch...finallyfor risky code, andthrow new Error()for your own problems. - Debug with the console and the debugger, and never hide errors silently.