JavaScript Error and Exception Handling | Java Script Tutorial - Learn with VOKS
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
Back Next

JavaScript Error and Exception Handling

Learn this topic step-by-step with VOKS Tutorials.

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


// 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);
}
QUICK KNOWLEDGE CHECK

Test Your Understanding

Answer 5 questions generated from this lesson. Your result is calculated instantly and is not saved.

0 / 5 answered
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
Course contents
Java Script
01 Introduction 02 Application of JavaScript 03 Defining JavaScript 04 Client-Side JavaScript 05 JavaScript Syntax 06 JavaScript Varaibles 07 JavaScript Operators 08 JavaScript Statements 09 JavaScript Arrays 10 Sorting JavaScript Array 11 JavaScript Functions 12 JavaScript Objects 13 JavaScript For and For-In Loops 14 JavaScript Cookies 15 JavaScript Form Validation 16 JavaScript Error and Exception Handling 17 JavaScript Animation 18 JavaScript Switch Case and While Loops