Suggest an editImprove this articleRefine the answer for “Errors inside functions”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)Errors inside a function are handled with **`try...catch`** for synchronous code, `try...catch` inside `async` functions for asynchronous code, and `.catch()` for promises without `await`. **Key point:** use `try...catch` precisely, where you actually expect an error, and return a predictable value (`null`, `{}`, `false`) on failure instead of silencing errors without logging.Shown above the full answer for quick recall.Answer (EN)Image## 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 `try` runs "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).For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.