CS Engineering Gyan

JavaScript Error Handling

Error Handling is an important concept in JavaScript that allows developers to identify, manage, and respond to errors that occur during program execution.

Errors are common in programming. They may occur because of incorrect syntax, invalid data, network problems, or unexpected user input. Proper error handling prevents applications from crashing and improves user experience.

Professional JavaScript applications use error handling techniques to display meaningful messages, recover from failures, and maintain smooth program execution.


What is Error Handling in JavaScript?

Error handling is the process of detecting errors and controlling what happens when an error occurs in a program.

Instead of stopping the complete application, JavaScript allows developers to handle errors gracefully using special statements such as:


Why is Error Handling Important?

Without proper error handling, a small mistake can stop the execution of an entire program.

Advantages of Error Handling


Types of Errors in JavaScript

JavaScript errors can occur due to different reasons. Understanding error types helps developers solve problems faster.

Error Type Description
Syntax Error Occurs when JavaScript code violates language rules.
Runtime Error Occurs while the program is executing.
Logical Error Program runs but produces incorrect results.
Reference Error Occurs when using an undefined variable.
Type Error Occurs when an operation is performed on an incorrect data type.

Syntax Error

A syntax error occurs when JavaScript code is written incorrectly according to language rules.

Example


let name = "JavaScript

console.log(name);


The missing quotation mark creates a syntax error.


Runtime Error

A runtime error occurs while executing the program.

Example


let number = 10;


console.log(number.toUpperCase());


The program runs but generates an error because numbers do not have the toUpperCase() method.


Logical Error

Logical errors are mistakes in program logic. The code executes successfully but produces incorrect output.

Example


let price = 100;


let discount = 10;


let finalPrice = price + discount;


console.log(finalPrice);


The calculation logic is incorrect because discount should be subtracted.


The try Statement

The try statement contains code that may generate an error. JavaScript attempts to execute this code and checks whether any problem occurs.

Syntax


try
{

// Code that may produce error

}



Example of try Statement


try
{

let result =
10 / 0;


console.log(result);


}


The try block allows developers to test code that may cause unexpected problems.


The catch Statement

The catch block handles errors generated inside the try block.

When an error occurs, JavaScript immediately moves from the try block to the catch block.

Syntax


try
{

// Risky code

}

catch(error)
{

// Handle error

}



Example Using try and catch


try
{

console.log(variable);


}

catch(error)
{

console.log("An error occurred");


}


Output


An error occurred

The program continues running instead of stopping completely.



The finally Statement

The finally statement is used to execute code after the try and catch blocks. The finally block always runs whether an error occurs or not.

It is commonly used for cleanup operations such as closing connections, hiding loading messages, releasing resources, or performing final tasks.

Syntax


try
{

// Code that may generate error

}

catch(error)
{

// Handle error

}

finally
{

// Always executed

}


Example of finally Statement


try
{

let value = 20;

console.log(value);


}

catch(error)
{

console.log("Error Found");


}

finally
{

console.log("Program Completed");


}

Output


20

Program Completed

The finally block executes after the try block completes successfully.


Example When Error Occurs


try
{

console.log(username);


}

catch(error)
{

console.log("Variable not found");


}

finally
{

console.log("Execution Finished");


}

Output


Variable not found

Execution Finished


The throw Statement in JavaScript

The throw statement allows developers to create custom errors manually. It is used when a programmer wants to generate an error based on specific conditions.

Using throw, developers can stop normal program execution and send a meaningful error message.

Syntax


throw expression;


Example of throw Statement


let age = 15;


if(age < 18)
{

throw "Age must be 18 or above";


}

Output


Age must be 18 or above


Using throw with try...catch

The throw statement is usually combined with try and catch so that custom errors can be handled properly.

Example


try
{

let marks = 25;


if(marks < 40)
{

throw new Error("Student Failed");


}


}

catch(error)
{

console.log(error.message);


}

Output


Student Failed


Creating Custom Errors

Custom errors help developers provide clear information about specific problems in an application.

Instead of showing technical messages, applications can display user-friendly error messages.

Example


function checkPassword(password)
{


if(password.length < 8)
{

throw new Error(
"Password must contain minimum 8 characters"
);


}


}


try
{

checkPassword("abc");


}

catch(error)
{

console.log(error.message);


}

Output


Password must contain minimum 8 characters


JavaScript Error Object

JavaScript provides an Error object that contains information about errors generated during program execution.

Common Error Object Properties

Property Description
name Returns the name of the error.
message Returns the error description.
stack Provides detailed error information and location.

Example Using Error Object


try
{

let number;


console.log(number.toUpperCase());


}

catch(error)
{

console.log(error.name);

console.log(error.message);


}

Output


TypeError

Cannot read properties of undefined


Common Built-in Error Types

JavaScript provides different built-in error objects for identifying specific problems.

Error Type Purpose
Error General error object.
ReferenceError Occurs when accessing an undefined variable.
TypeError Occurs when using an invalid operation on a value.
RangeError Occurs when a value is outside the allowed range.
SyntaxError Occurs due to invalid JavaScript syntax.
URIError Occurs while handling invalid URI functions.

Handling User Input Errors

User input is one of the most common sources of errors in web applications. Developers should validate and handle incorrect data properly.

Example


try
{

let age =
prompt("Enter your age");


if(age == "")
{

throw new Error("Age cannot be empty");


}


console.log(age);


}

catch(error)
{

alert(error.message);


}


Form Validation Error Handling

JavaScript error handling is widely used in forms to check incorrect user information before sending data to the server.

Example


function submitForm()
{


let email =
document.getElementById("email").value;


try
{


if(email == "")
{

throw new Error(
"Email field is required"
);


}


alert("Form Submitted");


}

catch(error)
{

alert(error.message);


}


}


Advantages of Using try...catch


Real-World Applications of Error Handling



Debugging JavaScript Errors

Debugging is the process of finding and fixing errors in a JavaScript program. Every developer faces errors while writing code, and debugging skills help identify the exact cause of problems quickly.

Modern browsers provide powerful developer tools that make debugging easier by showing error messages, code locations, and execution details.


Using Browser Developer Tools

Most modern browsers include built-in developer tools. These tools help developers inspect code, view errors, test programs, and analyze application behaviour.

Opening Developer Tools

Important Developer Tool Sections

Tool Purpose
Console Displays errors and allows testing JavaScript code.
Sources Helps debug JavaScript files using breakpoints.
Network Shows API requests and network problems.
Elements Inspects HTML and CSS code.

Using console Methods for Debugging

The console object provides different methods that help developers test and debug JavaScript programs.

console.log()

The console.log() method displays information in the browser console.


let age = 20;


console.log(age);


Output


20


console.error()

The console.error() method displays error messages.

Example


console.error("Invalid Login");



console.warn()

The console.warn() method displays warning messages during development.

Example


console.warn("Password is weak");



Handling API Errors

Modern websites frequently communicate with servers using APIs. Network failures, invalid responses, and server problems can create errors.

Proper error handling ensures that users receive helpful messages instead of blank screens or broken pages.

Example Using fetch()


fetch("https://example.com/data")


.then(response =>
{


if(!response.ok)
{

throw new Error("Unable to load data");


}


return response.json();


})


.catch(error =>
{


console.log(error.message);


});



Handling JSON Parsing Errors

JSON data is commonly used for exchanging information between client and server. Invalid JSON data can generate errors.

Example


try
{


let data =
JSON.parse("invalid json");


}


catch(error)
{


console.log("Invalid JSON Data");


}



Handling Network Failures

Internet connection problems can interrupt web applications. Developers should handle such situations properly.

Example


try
{


// Network operation


}

catch(error)
{


console.log(
"Please check your internet connection"
);


}



Error Handling Best Practices

Following good practices makes JavaScript applications more reliable and easier to maintain.


Common Mistakes in Error Handling


Difference Between Errors and Exceptions

Errors Exceptions
Problems generated by incorrect code or environment. Problems intentionally handled during program execution.
May stop program execution. Can be managed using try...catch.
Example: Syntax Error. Example: Custom validation error.

Error Handling in Large Applications

Large applications require organized error management strategies. Developers usually create common error handling systems to manage problems consistently.

Examples


JavaScript Error Handling Interview Questions

  1. What is error handling in JavaScript?
  2. Why is error handling important?
  3. Explain try and catch statements.
  4. What is the purpose of finally block?
  5. What is the use of throw statement?
  6. How can we create custom errors?
  7. What is the Error object in JavaScript?
  8. Explain ReferenceError and TypeError.
  9. How do you debug JavaScript errors?
  10. What is the difference between syntax error and logical error?
  11. How can API errors be handled?
  12. What are console methods used for debugging?
  13. Why should developers avoid empty catch blocks?
  14. How does error handling improve user experience?
  15. What are best practices for JavaScript error handling?

Summary

JavaScript Error Handling is an essential skill for creating reliable and professional web applications. Errors can occur due to invalid code, incorrect user input, network failures, or unexpected situations.

JavaScript provides powerful mechanisms such as try, catch, finally, and throw to detect and manage errors effectively.

Proper error handling improves application stability, makes debugging easier, and provides a better experience for users. Understanding these concepts helps developers build secure, maintainable, and error-resistant JavaScript applications.


← Previous: JavaScript Timers Next: Modern JavaScript (ES6+ Features) →
Home Visit Our YouTube Channel