JavaScript Error Handling helps you manage runtime errors so your program doesn’t crash unexpectedly. Let’s break down each keyword clearly:
🔹 1. try
The try block contains code that might cause an error.
👉 JavaScript will attempt to run this code.
try {
let result = 10 / x; // x is not defined → error
}
🔹 2. catch
The catch block runs if an error occurs in try.
👉 It receives the error object (you can name it anything, usually err).
try {
let result = 10 / x;
} catch (err) {
console.log("Error occurred:", err.message);
}
✔ Output:
Error occurred: x is not defined
🔹 3. finally
The finally block always executes, whether an error happens or not.
👉 Useful for cleanup tasks (closing connections, stopping loaders, etc.)
try {
console.log("Trying...");
} catch (err) {
console.log("Error:", err.message);
} finally {
console.log("This always runs");
}
✔ Output:
Trying...
This always runs
🔹 4. throw
The throw statement is used to create your own custom error.
👉 You can throw:
- String
- Number
- Boolean
- Object (best practice: use
Error)
function checkAge(age) {
if (age < 18) {
throw new Error("You must be 18 or older");
}
return "Access granted";
}try {
console.log(checkAge(16));
} catch (err) {
console.log(err.message);
}
✔ Output:
You must be 18 or older
🔥 Full Example (All Together)
try {
let age = 15; if (age < 18) {
throw new Error("Underage user");
} console.log("Access granted");} catch (err) {
console.log("Caught error:", err.message);} finally {
console.log("Execution finished");
}
🧠 Key Points
try→ test codecatch→ handle errorsfinally→ always runsthrow→ create custom errors
🚀 Interview Tip
- Always use
Errorobject inthrow:
throw new Error("Something went wrong");






