What is an exception?
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:
- The
dividefunction runs. - The condition
b === 0is true, and the engine "throws" the error object. - This event is the exception.
- JavaScript starts looking for the nearest
try...catch. - The
catchblock 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
- Automatic (unhandled) Occur when the engine itself throws an error:
javascript
console.log(a); // ReferenceError → exception thrown automatically- 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 executionShort Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.