Skip to main content

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:

  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)

KeywordWhat it does
tryThe block where an error might occur
throwThrows an exception
catchCatches the exception and handles it
finallyAlways 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
  1. 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

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.