Error Handling in JavaScript: Try, Catch, Finally
Introduction
While writing JavaScript code, errors are unavoidable.
Sometimes errors occur due to:
Invalid input
Network failures
Unexpected conditions
If we do not handle these errors properly, our application may crash or behave unpredictably.
To manage this, JavaScript provides:
try, catch, and finally
These help us handle errors gracefully and keep our application stable.
What Are Errors in JavaScript?
Errors are problems that occur during the execution of a program.
Example of a Runtime Error:
console.log(user.name);
Problem:
useris not definedJavaScript throws an error and stops execution
Why Error Handling Matters
Without error handling:
The application can crash
Users may see broken UI
Debugging becomes difficult
With proper error handling:
The app continues running
Errors are managed gracefully
Debugging becomes easier
Using try and catch
The try...catch block is used to handle errors.
Syntax:
try {
// code that may cause an error
} catch (error) {
// code to handle the error
}
Example:
try {
let result = user.name;
console.log(result);
} catch (error) {
console.log("An error occurred:", error.message);
}
Explanation:
Code inside
tryis executedIf an error occurs, execution moves to
catchThe error is handled without crashing the program
Graceful Failure
Instead of crashing, we can show a meaningful message:
try {
let data = JSON.parse("invalid json");
} catch (error) {
console.log("Invalid JSON format");
}
This improves user experience.
The finally Block
The finally block always executes:
- Whether an error occurs or not
Syntax:
try {
// code
} catch (error) {
// handle error
} finally {
// always runs
}
Example:
try {
console.log("Trying...");
} catch (error) {
console.log("Error occurred");
} finally {
console.log("This always runs");
}
Output:
Trying...
This always runs
Throwing Custom Errors
We can create our own errors using throw.
Example:
function checkAge(age) {
if (age < 18) {
throw new Error("You must be 18 or older");
}
return "Access granted";
}
try {
console.log(checkAge(15));
} catch (error) {
console.log(error.message);
}
Benefit:
Helps define custom rules
Makes debugging easier
Error Handling with Async/Await
In asynchronous code, errors are handled using try...catch.
Example:
async function fetchData() {
try {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
} catch (error) {
console.log("Failed to fetch data");
}
}
Error Handling Flow (Concept)
Try Block → Error Occurs → Catch Block Executes → Finally Block Executes
If no error:
Try Block → No Error → Finally Block Executes
Common Mistakes
Not using
try...catchin risky codeIgnoring error messages
Overusing
try...catchunnecessarily
Interview Points
Errors occur during runtime
trycontains risky codecatchhandles errorsfinallyalways executesthrowis used for custom errors
Conclusion
Error handling is a critical part of writing reliable JavaScript code:
Prevents application crashes
Improves user experience
Helps in debugging
Using try, catch, and finally, we can build more robust and maintainable applications.