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:


 Syntax Errors

These happen when the code violates JS rules.

Example:

Output:

Uncaught SyntaxError: Unexpected token ')'

Runtime Errors

These occur while the code is running.

Example:

Output:

ReferenceError: x is not defined

 Logical Errors

The code runs but produces unexpected results.

Example:

Result is incorrect, but no error message occurs.



 Common JavaScript Error Types

Error TypeMeaningExample
ReferenceErrorUsing a variable that doesn’t existconsole.log(a);
SyntaxErrorCode grammar errorif (true {}
TypeErrorWrong operation on a data type"hello"()
RangeErrorValue out of allowed range.repeat(-1)
URIErrorInvalid URL encodingdecodeURI("%")
EvalErrorIssues with eval() function (rare)eval("break")

 Handling Errors with try...catch

It 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

FeatureMeaning
Js errors help find mistakesYes
Different types: Syntax, Runtime, LogicalYes
Use try...catch to avoid breaking programYes
You can throw custom errorsYes

You may also like...