What is an exception
An exception is an event that occurs while the program is running, when an error happens and the normal execution of the code is interrupted. In other words, an exception is a "signal" about an error situation that the JavaScript engine throws (throw) and that you can catch (catch).
Theory
TL;DR
- An exception is the moment an error is thrown, while
Erroris the object holding information about what went wrong. - An exception interrupts the normal flow of execution and starts the search for the nearest
try...catch. - The mechanism rests on four keywords:
try,throw,catch,finally. - Exceptions are either automatic (thrown by the engine) or user defined (thrown by the developer with
throw). - If nobody catches an exception, it bubbles up the call stack and the program terminates with an error.
Quick example
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
return a / b;
}
try {
divide(5, 0); // here the exception is thrown
} catch (err) {
console.log("Caught exception:", err.message);
}Definition
An exception is an event that arises while the program is running, when an error happens and the normal execution of the code is interrupted.
Put differently, an exception is a "signal" about an error situation that the JavaScript engine throws (throw) and that can be caught (catch).
The difference between error and exception
- Error is an object that carries information about what went wrong.
- Exception is the moment when that error object was thrown during execution.
Put differently: Error is the data, Exception is the event of throwing that data.
How an exception actually arises
Let us walk through the example above step by step:
- The
dividefunction runs. - The condition
b === 0is true, and the engine throws an error object. - That event is the exception.
- JavaScript starts looking for the nearest
try...catch. - The
catchblock intercepts the exception, and the program keeps running.
The exception mechanism: try / throw / catch / finally
| Keyword | What it does |
|---|---|
try | The block where an error may happen |
throw | Throws an exception |
catch | Intercepts the exception and handles it |
finally | Always runs, even if there was an error |
Example:
try {
throw new Error("Network error");
} catch (error) {
console.log("Caught exception:", error.message);
} finally {
console.log("This code always runs");
}Two kinds of exceptions
-
Automatic (thrown by the engine). They appear when the engine itself detects an error:
javascriptconsole.log(a); // ReferenceError, the exception is thrown automatically -
User defined (explicit). When the programmer throws the exception themselves:
javascriptthrow new Error("Something went wrong");
What happens if an exception is not caught
If an exception is not intercepted (there is no catch block), it bubbles up the call stack. If in the end nobody caught it, the program terminates with an error:
function a() { b(); }
function b() { throw new Error("Failure"); }
a(); // the error will terminate executionIn the browser such an exception ends up in the console and, if you want, in the global window.onerror handler; in Node.js the uncaughtException event terminates the process by default.
Common mistakes
- Confusing
Errorand an exception. Creatingnew Error("...")on its own interrupts nothing: it becomes an exception only afterthrow. - An empty
catch. Acatch {}block with no handling hides the problem: the program runs on in a broken state and you can no longer see the cause. - Expecting
try...catchto catch an asynchronous error. An exception thrown inside asetTimeoutcallback or in an unhandled promise will not reach the surroundingtry...catch; promises needawaitinsidetry, or.catch(). - Throwing something that is not an error object.
throw "text"is technically allowed, but then you have neithermessagenorstack; always thrownew Error(...)or a subclass of it. - Forgetting that
finallyruns even afterreturn. Areturninsidefinallyoverwrites the value returned fromtryand can silently swallow the exception.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.