Error handling in JavaScript is essential to gracefully manage unexpected problems during code execution. It helps prevent your program from crashing and allows you to respond to errors effectively.
1. The try...catch Statement
The try...catch block lets you test a block of code for errors, and handle them if they occur:
try: Contains code that might throw an error.catch: Runs if an error occurs insidetry. Receives the error object.
📌 Deep Dive: Basic try...catch
try {
JSON.parse("invalid json");
} catch (error) {
console.log("Error caught:", error.message);
}
2. The finally Clause
The finally block always executes after try and catch, regardless of whether an error was thrown or caught. Useful for cleanup tasks.
📌 Deep Dive: Using finally
try {
throw new Error("Oops!");
} catch (e) {
console.log("Handling error:", e.message);
} finally {
console.log("This always runs.");
}
3. Throwing Custom Errors
You can create and throw your own errors with throw. Useful for input validation or domain-specific error handling.
📌 Deep Dive: Throwing errors
function checkAge(age) {
if (age < 18) {
throw new Error("Underage: Access denied");
}
return "Access granted";
}
try {
console.log(checkAge(15));
} catch (err) {
console.log(err.message);
}

💡 Best Practice
Only use try...catch around code where you expect errors. Avoid catching errors silently without handling them, as it can hide bugs.
| Approach | Description |
|---|---|
try...catch | Catches and handles runtime errors. |
throw | Manually triggers an error to be caught or propagate. |
finally | Runs cleanup code regardless of errors. |
⚠️ Avoid Overusing try...catch
Wrapping too much code in try...catch can degrade performance and obscure bugs. Use it selectively for risky operations.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does the catch block do in a try...catch statement?
Question 2 of 2
Which clause always runs after try and catch blocks?
Loading results...