Error Handling in JavaScript (try, catch, finally, throw)
Every JavaScript program can encounter unexpected issues such as wrong user input, missing data, network failures, invalid JSON, undefined variables, and other runtime errors. Without proper error handling, applications may crash unexpectedly. JavaScript provides structured mechanisms to handle these issues safely.
Key Error-Handling Tools
try
catch
finally
throw
1. try…catch
The try block contains code that may cause an error, while the catch block safely handles the error.
Example:
try {
console.log(x); // x is not defined
} catch (error) {
console.log("Error occurred:", error.message);
}
Output:
Error occurred: x is not defined
The program continues running instead of crashing.
2. finally Block
The finally block always executes, whether an error occurred or not.
Example:
try {
console.log("Trying...");
throw new Error("Something went wrong");
} catch (e) {
console.log("Caught:", e.message);
} finally {
console.log("This will always run");
}
Output:
Trying...
Caught: Something went wrong
This will always run
3. throw — Creating Custom Errors
You can create and throw your own custom errors.
Example:
function checkAge(age) {
if (age < 18) {
throw "You must be 18 or older";
}
return "Access granted";
}
try {
console.log(checkAge(16));
} catch (e) {
console.log("Error:", e);
}
Output:
Error: You must be 18 or older
The throw statement stops execution and jumps into the catch block.
4. Handling JSON Errors
try {
let data = JSON.parse("{ name: 'Aman' }"); // invalid JSON
} catch (e) {
console.log("Invalid JSON:", e.message);
}
5. Real-Life Example: Login Validation
function login(user) {
if (!user) throw "User not found";
return "Login successful";
}
try {
console.log(login(null));
} catch (e) {
console.log("Login Error:", e);
}
Output:
Login Error: User not found
6. Nested try…catch
try {
try {
throw new Error("Inner error");
} catch (e) {
console.log("Inner Catch:", e.message);
}
console.log(a); // undefined variable
} catch (e) {
console.log("Outer Catch:", e.message);
}
7. try…catch with async/await
Error handling works similarly with async/await.
function getData() {
return new Promise((resolve, reject) => {
reject("Server down");
});
}
async function load() {
try {
let data = await getData();
console.log(data);
} catch (e) {
console.log("Error:", e);
}
}
load();
8. try…catch Does Not Catch Syntax Errors
try…catch only handles runtime errors, not syntax issues such as:
Missing parentheses
Missing commas
Incorrect keywords
These errors occur before code execution.
Example Program (Complete)
function divide(a, b) {
if (b === 0) throw "Cannot divide by zero";
return a / b;
}
try {
console.log(divide(10, 2)); // OK
console.log(divide(10, 0)); // Error
} catch (e) {
console.log("Error:", e);
} finally {
console.log("Calculation done");
}
Output:
5
Error: Cannot divide by zero
Calculation done
Common Mistakes Beginners Make
Using try…catch excessively (use only when needed)
Forgetting that finally always runs
Throwing vague or unclear error messages
Not handling async/await errors
Mixing different error types (strings vs Error objects)
Practice Tasks (Do It Yourself)
Create a function that throws an error if input is not a number.
Parse invalid JSON and handle the error.
Add a finally block to any example.
Create custom error messages using throw.
Use try…catch with async/await to simulate an API call.