Error handling helps us identify and manage problems in a program. It prevents unexpected failures and helps us display useful messages when something goes wrong.
An error is a problem that occurs while a program is being written or executed. Different types of errors require different solutions.
| Error Type | Meaning | Example |
|---|---|---|
| Syntax Error | Code does not follow JavaScript syntax rules. | if (x > 5 { } |
| Reference Error | A variable or identifier is not available. | console.log(unknownVariable); |
| Type Error | An operation is used with an incompatible value. | null.name |
| Range Error | A value is outside an allowed range. | new Array(-1) |
| Custom Error | An application creates its own error. | throw new Error("Invalid input"); |
The try...catch statement allows us to handle errors
instead of letting them interrupt the normal flow of the program.
try {
console.log(unknownVariable);
} catch (error) {
console.log("An error occurred");
}
console.log("Program continues");
An error occurred
Program continues
The undefined variable causes a ReferenceError. The catch block handles it, allowing the program to continue.
JavaScript errors usually provide useful properties such as
name and message. The stack
property can also help developers locate where an error occurred.
try {
throw new Error("Something went wrong");
} catch (error) {
console.log("Name:", error.name);
console.log("Message:", error.message);
}
Name: Error
Message: Something went wrong
The error.message property contains the
descriptive message supplied when the Error object was created.
The throw statement lets us create an error when a
condition is not valid.
function checkAge(age) {
if (age < 18) {
throw new Error("You must be at least 18");
}
return "Access allowed";
}
try {
console.log(checkAge(16));
} catch (error) {
console.log(error.message);
}
You must be at least 18
When the age is below 18, the function throws an error. The surrounding catch block handles it.
The finally block runs after the try/catch process,
whether an error occurs or not. It is useful for cleanup operations.
try {
console.log("Starting program");
throw new Error("Something failed");
} catch (error) {
console.log("Error:", error.message);
} finally {
console.log("Program finished");
}
Starting program
Error: Something failed
Program finished
Errors in asynchronous code need appropriate handling. When using
async and await, wrap awaited operations in try...catch
to handle rejected Promises.
function getData() {
return new Promise(function(resolve, reject) {
reject(new Error("Unable to get data"));
});
}
async function showData() {
try {
const data = await getData();
console.log(data);
} catch (error) {
console.log("Error:", error.message);
}
}
showData();
Error: Unable to get data
The rejected Promise causes the await expression to throw. The catch block handles the error.
When working with files, errors may occur if a file does not exist or the program does not have permission to access it. Node.js provides callback-based and Promise-based file system APIs.
const fs = require("fs");
fs.readFile("student.txt", "utf8", function(error, data) {
if (error) {
console.log("Unable to read file:", error.message);
return;
}
console.log(data);
});
Save this code in a JavaScript file and run it with Node.js.
If student.txt is missing or cannot be read,
the error is handled by the callback.
You can create your own error class when an application needs errors with specific names or additional information.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function registerUser(username) {
if (!username) {
throw new ValidationError("Username is required");
}
return "User registered";
}
try {
console.log(registerUser(""));
} catch (error) {
if (error instanceof ValidationError) {
console.log(error.name + ":", error.message);
} else {
console.log("Unexpected error:", error.message);
}
}
ValidationError: Username is required
Select the correct answer for each question.