JavaScript Errors
An error is the browser's report that a piece of code failed. The report names the problem so the broken line can be found.
Catching an error
The name y was never declared, so the try block fails. The catch block logs the error name, and the script carries on.
try {
const total = y + 1;
console.log(total);
} catch (err) {
console.log(err.name);
}
console.log("Still running");The error message
The message describes the failure in words. Here the message names the missing variable.
try {
const total = y + 1;
console.log(total);
} catch (err) {
console.log(err.message);
}Throwing an error
throw raises an error on purpose. The catch block receives it like any other error.
try {
throw new Error("Too small");
} catch (err) {
console.log(err.message);
}Example
const score = 150;
try {
if (score > 100) {
throw new Error("Score too high");
}
console.log("Score accepted");
} catch (err) {
console.log(err.name);
console.log(err.message);
}
console.log("Check finished");Key points
- An uncaught error stops the script at the line that failed.
- try: a block that runs code which might fail.
- catch: the block that receives the error when the try block fails.
- The error object carries a name and a message.
- finally: a block after try and catch that always runs.
In this example, the score sits above the allowed limit. The throw statement raises an error with a custom message. The catch block logs the error name and the message. The final line proves the script survived.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which block receives an error from a failed try block?