JavaScript Errors

JavaScript Tutorial

JavaScript Errors

In JavaScript Errors when something goes wrong while the program runs. They help you detect bugs and fix them.

JavaScript errors fall into two main categories:


1️⃣ Syntax Errors

These happen when the code violates JS rules.

Example:


Output:

Uncaught SyntaxError: Unexpected token ')'

2️⃣ Runtime Errors

These occur while the code is running.

Example:


Output:

ReferenceError: x is not defined

3️⃣ Logical Errors

The code runs but produces unexpected results.

Example:


Result is incorrect, but no error message occurs.



🧩 Common JavaScript Error Types

Error Type Meaning Example
ReferenceError Using a variable that doesn’t exist console.log(a);
SyntaxError Code grammar error if (true {}
TypeError Wrong operation on a data type "hello"()
RangeError Value out of allowed range .repeat(-1)
URIError Invalid URL encoding decodeURI("%")
EvalError Issues with eval() function (rare) eval("break")

🛠 Handling Errors with try...catch

JavaScript allows handling errors using try, catch, and optionally finally.


Output:

Error caught: ReferenceError: y is not defined

🧹 Adding finally Block

The finally block always executes, whether an error happens or not.



🚨 Throwing Custom Errors

You can create your own error messages with throw.


 

Output:

Uncaught Age cannot be negative!

🔍 Checking Error Name and Message



🎯 Summary

Feature Meaning
Js errors help find mistakes
Different types: Syntax, Runtime, Logical
Use try...catch to avoid breaking program
You can throw custom errors

You may also like...