Suggest an editImprove this articleRefine the answer for “What is an exception?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)An **exception** is an event that occurs during program execution when an error happens, interrupting the normal flow of code. **Key point:** an exception is a "signal" about an error condition that the JavaScript engine "throws" and that can be "caught" with `catch`.Shown above the full answer for quick recall.Answer (EN)Image## Definition An **exception** is an **event** that occurs **during program execution** when an error happens, and **normal code execution is interrupted**. In other words, an **exception is a "signal" about an error condition**, which the JavaScript engine "throws" and which can be "caught". ## The difference between error and exception - **Error** is an **object** that contains information about what went wrong. - **Exception** is the **moment** when that error object **was thrown** during execution. > In other words: > * *Error* is **data**, > * *Exception* is the **event of throwing that data**. ## Example: how an exception occurs ```javascript function divide(a, b) { if (b === 0) { throw new Error("Cannot divide by zero!"); } return a / b; } try { divide(5, 0); // An exception occurs here } catch (err) { console.log("Caught exception:", err.message); } ``` What happens: 1. The `divide` function runs. 2. The condition `b === 0` is true, and the engine **"throws" the error object**. 3. This event is the **exception**. 4. JavaScript starts looking for the nearest `try...catch`. 5. The `catch` block **catches** the exception, and the program keeps running. ## The exception mechanism (try / throw / catch / finally) | Keyword | What it does | |---|---| | `try` | The block where an error might occur | | `throw` | Throws an exception | | `catch` | Catches the exception and handles it | | `finally` | Always runs - even if there was an error | Example: ```javascript try { throw new Error("Network error"); } catch (error) { console.log("Caught exception:", error.message); } finally { console.log("This code always runs"); } ``` ## There are two kinds of exceptions 1. **Automatic (unhandled)** Occur when the engine itself throws an error: ```javascript console.log(a); // ReferenceError → exception thrown automatically ``` 2. **User-defined (explicit)** When the programmer throws an exception themselves: ```javascript throw new Error("Something went wrong!"); ``` ## What happens if an exception isn't caught If an exception is **not caught** (no `catch`), it "bubbles up" the call stack. If, in the end, nobody catches it, the program **terminates with an error**: ```javascript function a() { b(); } function b() { throw new Error("Error!"); } a(); // The error terminates execution ```For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.