Errors inside functions
1. Synchronous error handling (try...catch)
Used when an error can occur while the function is running.
javascript
function divide(a, b) {
try {
if (b === 0) {
throw new Error("Division by zero is not possible");
}
return a / b;
} catch (error) {
console.error("Error:", error.message);
return null; // Return a safe value
}
}
console.log(divide(10, 0)); // Error: Division by zero is not possible- Everything inside
tryruns "under protection". - If an error occurs, execution moves to
catch. - After that, the program does not crash.
2. Asynchronous errors (async/await)
For async functions, you need to use try...catch inside the async block.
javascript
async function fetchUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error("User not found");
return await res.json();
} catch (error) {
console.error("Request error:", error.message);
return null;
}
}3. Errors in promises
If you are not using await, errors can be caught via .catch().
javascript
fetch("/api/data")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error("Error:", err));4. Creating and rethrowing errors manually
Sometimes you need not only to catch an error, but also to pass it up.
javascript
function parseJSON(str) {
try {
return JSON.parse(str);
} catch (error) {
throw new Error("Invalid JSON: " + error.message);
}
}
try {
parseJSON("{invalid}");
} catch (e) {
console.error("Top level caught:", e.message);
}5. Good practices
Use try...catch precisely, where you actually expect an error.
Do not silence errors without logging.
Return a predictable value (null, {}, false) on failure.
For server-side functions, log via logger, Sentry, console.error.
For pure functions, throw the error instead of logging it (let the calling code decide).
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.