Error Handling in JavaScript
JavaScript provides built-in mechanisms to handle errors, making your code more robust and fault-tolerant. The most common approach is using the try...catch
statement.
🛠️ try...catch Syntax
try {
// Code that might throw an error
let result = riskyFunction();
console.log(result);
} catch (error) {
// Code to run if an error occurs
console.error("❌ Error:", error.message);
}
⚠️ Common Error Example
try {
nonExistentFunction(); // This will throw a ReferenceError
} catch (err) {
console.error("Caught error:", err);
}
✅ Optional finally Block
Use finally
to run code after try/catch
regardless of the outcome.
try {
console.log("Trying something risky...");
} catch (err) {
console.error("Caught an error");
} finally {
console.log("Always runs this block.");
}
🚨 Throwing Custom Errors
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (e) {
console.error("Custom Error:", e.message);
}
📦 Async Error Handling
Use try...catch
inside async
functions for asynchronous error handling.
async function fetchData() {
try {
const res = await fetch("https://api.example.com/data");
const data = await res.json();
console.log(data);
} catch (err) {
console.error("Fetch error:", err);
}
}
💡 Tip: Always handle both synchronous and asynchronous errors to prevent app crashes.