JavaScript Error and Exception Handling | Java Script Tutorial - Learn with VOKS
Back Next

JavaScript Error and Exception Handling


When you write JavaScript code, sometimes things go wrong. These problems are called errors.

Understanding errors is very important because:

  • They help you find mistakes in your code.
  • They prevent your program from crashing unexpectedly.
  • They make your applications more reliable.

What Is an Error?

An error is something that stops your program from running correctly.

In JavaScript, errors are generally grouped into:

  1. Syntax Errors
  2. Logical Errors
  3. Runtime Errors (Exceptions)

Let’s explain each one clearly.


1️⃣ Syntax Errors

A syntax error happens when you break the rules of JavaScript grammar.

Think of it like a spelling or grammar mistake in English.

Example of a Syntax Error

console.log("Hello World"

❌ Problem: Missing closing parenthesis )

JavaScript will stop immediately and show an error like:

SyntaxError: missing ) after argument list

Another Example

let number = 10
if (number > 5 {
  console.log("Greater than 5");
}

❌ Missing closing parenthesis ) in if statement.


Important:

Syntax errors must be fixed before the program can run.


2️⃣ Logical Errors

A logical error happens when your program runs without crashing, but gives the wrong result.

This is harder to detect because there is no error message.

Example of Logical Error

let a = 10;
let b = 5;

let result = a - b;  // We meant to add

console.log(result);

If you wanted addition but wrote subtraction, the result will be wrong — but JavaScript will not complain.


Another Example

let age = 18;

if (age > 18) {
  console.log("You are an adult.");
}

Problem:

If age is exactly 18, nothing happens.

Maybe we meant:

if (age >= 18)

Important:

Logical errors are fixed by testing and debugging.


3️⃣ Runtime Errors (Exceptions)

A runtime error happens while the program is running.

These are also called exceptions.

Example: Trying to use something that doesn’t exist.


Example of Runtime Error

let user;
console.log(user.name);

user is undefined, so accessing .name causes:

TypeError: Cannot read properties of undefined

Another Example

let number = 10;
number();  // Trying to call a number like a function

This causes:

TypeError: number is not a function


What Is Exception Handling?

Exception handling allows you to:

  • Catch runtime errors
  • Prevent program crashes
  • Show friendly error messages

JavaScript uses:

  • try
  • catch
  • finally
  • throw


try...catch Syntax

try {
  // Code that might cause an error
} catch (error) {
  // Code that runs if an error occurs
}

Example

try {
  let user;
  console.log(user.name);
} catch (error) {
  console.log("An error occurred!");
}

Instead of crashing, it prints:

An error occurred!


Understanding the Error Object

Inside catch, the error object contains information.

try {
  let number = 10;
  number();
} catch (error) {
  console.log(error.name);     // TypeError
  console.log(error.message);  // number is not a function
}


finally Block

finally always runs — whether there is an error or not.

try {
  console.log("Start");
} catch (error) {
  console.log("Error happened");
} finally {
  console.log("This always runs");
}


throw Keyword

You can create your own errors using throw.

let age = 15;

try {
  if (age < 18) {
    throw "You must be 18 or older.";
  }
  console.log("Access granted");
} catch (error) {
  console.log(error);
}


Built-in JavaScript Error Types

Some common built-in errors:

Example of ReferenceError

console.log(x);  // x not declared


Example Code:
// 1️⃣ Logical Error Example
let a = 10;
let b = 5;

// We intended addition but used subtraction
let result = a - b;
console.log("Logical Error Result (should be 15):", result);


// 2️⃣ Runtime Error Example with try...catch
try {
  let user;
  console.log(user.name);  // This causes runtime error
} catch (error) {
  console.log("Caught an error!");
  console.log("Error Name:", error.name);
  console.log("Error Message:", error.message);
}


// 3️⃣ Using throw to create custom error
let age = 16;

try {
  if (age < 18) {
    throw new Error("You must be 18 or older.");
  }
  console.log("Access granted.");
} catch (error) {
  console.log("Custom Error:", error.message);
} finally {
  console.log("Age verification complete.");
}


// 4️⃣ Another Runtime Error Example
try {
  let number = 10;
  number();  // TypeError
} catch (error) {
  console.log("Another error caught:", error.message);
}
Java Script
Introduction Application of JavaScript Defining JavaScript Client-Side JavaScript JavaScript Syntax JavaScript Varaibles JavaScript Operators JavaScript Statements JavaScript Arrays Sorting JavaScript Array JavaScript Functions JavaScript Objects JavaScript For and For-In Loops JavaScript Cookies JavaScript Form Validation JavaScript Error and Exception Handling JavaScript Animation JavaScript Switch Case and While Loops
All Courses
Advance AI Bootstrap C C++ Computer Vision Content Writing CSS Cyber Security Data Analysis Deep Learning Email Marketing Excel Figma HTML Java Script Machine Learning MySQLi Node JS PHP Power Bi Python Python for AI Python for Analysis React React Native SEO SMM SQL