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.
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:
Without proper error handling, a small mistake can stop the execution of an entire program.
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. |
A syntax error occurs when JavaScript code is written incorrectly according to language rules.
let name = "JavaScript console.log(name);
The missing quotation mark creates a syntax error.
A runtime error occurs while executing the program.
let number = 10; console.log(number.toUpperCase());
The program runs but generates an error because numbers do not have the toUpperCase() method.
Logical errors are mistakes in program logic. The code executes successfully but produces incorrect output.
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 contains code that may generate an error. JavaScript attempts to execute this code and checks whether any problem occurs.
try
{
// Code that may produce error
}
try
{
let result =
10 / 0;
console.log(result);
}
The try block allows developers to test code that may cause unexpected problems.
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.
try
{
// Risky code
}
catch(error)
{
// Handle error
}
try
{
console.log(variable);
}
catch(error)
{
console.log("An error occurred");
}
An error occurred
The program continues running instead of stopping completely.
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.
try
{
// Code that may generate error
}
catch(error)
{
// Handle error
}
finally
{
// Always executed
}
try
{
let value = 20;
console.log(value);
}
catch(error)
{
console.log("Error Found");
}
finally
{
console.log("Program Completed");
}
20 Program Completed
The finally block executes after the try block completes successfully.
try
{
console.log(username);
}
catch(error)
{
console.log("Variable not found");
}
finally
{
console.log("Execution Finished");
}
Variable not found Execution Finished
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.
throw expression;
let age = 15;
if(age < 18)
{
throw "Age must be 18 or above";
}
Age must be 18 or above
The throw statement is usually combined with try and catch so that custom errors can be handled properly.
try
{
let marks = 25;
if(marks < 40)
{
throw new Error("Student Failed");
}
}
catch(error)
{
console.log(error.message);
}
Student Failed
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.
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);
}
Password must contain minimum 8 characters
JavaScript provides an Error object that contains information about errors generated during program execution.
| Property | Description |
|---|---|
| name | Returns the name of the error. |
| message | Returns the error description. |
| stack | Provides detailed error information and location. |
try
{
let number;
console.log(number.toUpperCase());
}
catch(error)
{
console.log(error.name);
console.log(error.message);
}
TypeError Cannot read properties of undefined
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. |
User input is one of the most common sources of errors in web applications. Developers should validate and handle incorrect data properly.
try
{
let age =
prompt("Enter your age");
if(age == "")
{
throw new Error("Age cannot be empty");
}
console.log(age);
}
catch(error)
{
alert(error.message);
}
JavaScript error handling is widely used in forms to check incorrect user information before sending data to the server.
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);
}
}
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.
Most modern browsers include built-in developer tools. These tools help developers inspect code, view errors, test programs, and analyze application behaviour.
| 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. |
The console object provides different methods that help developers test and debug JavaScript programs.
The console.log() method displays information in the browser console.
let age = 20; console.log(age);
20
The console.error() method displays error messages.
console.error("Invalid Login");
The console.warn() method displays warning messages during development.
console.warn("Password is weak");
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.
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);
});
JSON data is commonly used for exchanging information between client and server. Invalid JSON data can generate errors.
try
{
let data =
JSON.parse("invalid json");
}
catch(error)
{
console.log("Invalid JSON Data");
}
Internet connection problems can interrupt web applications. Developers should handle such situations properly.
try
{
// Network operation
}
catch(error)
{
console.log(
"Please check your internet connection"
);
}
Following good practices makes JavaScript applications more reliable and easier to maintain.
| 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. |
Large applications require organized error management strategies. Developers usually create common error handling systems to manage problems consistently.
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.