In this chapter, we will learn about error handling in JavaScript. Proper error handling is crucial for writing robust and reliable code. We will cover:
- What is Error Handling?
- Types of Errors
- Using
try...catch
- Using
finally
- Throwing Custom Errors
- Simple Programs using Error Handling
What is Error Handling?
Error handling is the process of catching and managing errors that occur during the execution of a program. By handling errors gracefully, you can prevent your program from crashing and provide meaningful feedback to users or developers.
Types of Errors
JavaScript errors can be categorized into several types:
- Syntax Errors: Occur when there is a mistake in the syntax of the code.
- Reference Errors: Occur when a non-existent variable is accessed.
- Type Errors: Occur when a value is not of the expected type.
- Range Errors: Occur when a value is not within the allowable range.
- Eval Errors: Occur when the
eval()
function is used incorrectly (not commonly used).
Examples
// Syntax Error
// console.log("Hello, World!)
// Reference Error
// console.log(nonExistentVariable);
// Type Error
// let num = 5;
// num.toUpperCase();
// Range Error
// let arr = new Array(-1);
// Eval Error
// eval('foo bar');
Using try…catch
The try...catch
statement allows you to catch and handle errors that occur in a block of code. If an error occurs in the try
block, the catch
block is executed.
Syntax
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
}
Example
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
console.log("An error occurred:", error.message);
}
Output:
Infinity
Using finally
The finally
block contains code that will be executed regardless of whether an error occurred in the try
block. It is useful for cleaning up resources or performing tasks that must always be completed.
Syntax
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that will always be executed
}
Example
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
console.log("An error occurred:", error.message);
} finally {
console.log("This will always be executed.");
}
Output:
Infinity
This will always be executed.
Throwing Custom Errors
You can throw custom errors using the throw
statement. This allows you to create meaningful error messages and handle specific error conditions.
Syntax
throw new Error("Custom error message");
Example
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
}
try {
let result = divide(10, 0);
console.log(result);
} catch (error) {
console.log("An error occurred:", error.message);
}
Output:
An error occurred: Division by zero is not allowed.
Simple Programs using Error Handling
Program 1: Validating User Input
function validateAge(age) {
if (isNaN(age)) {
throw new Error("Age must be a number.");
}
if (age < 0 || age > 120) {
throw new Error("Age must be between 0 and 120.");
}
return "Valid age: " + age;
}
try {
let userAge = validateAge(25);
console.log(userAge);
userAge = validateAge(-5); // This should trigger an error
} catch (error) {
console.log("An error occurred:", error.message);
}
Output:
Valid age: 25
An error occurred: Age must be between 0 and 120.
Program 2: Reading a JSON File
function parseJSON(jsonString) {
try {
let data = JSON.parse(jsonString);
console.log("Parsed JSON:", data);
} catch (error) {
console.log("An error occurred:", error.message);
}
}
let jsonString = '{"name": "Ramesh", "age": 25}';
parseJSON(jsonString);
jsonString = '{"name": "Ramesh", "age": 25'; // This should trigger an error
parseJSON(jsonString);
Output:
Parsed JSON: { name: 'Ramesh', age: 25 }
An error occurred: Unexpected end of JSON input
Conclusion
In this chapter, you learned about JavaScript error handling, including different types of errors, using try...catch
, using finally
, and throwing custom errors. We also provided various use cases with simple programs to demonstrate the usage of error handling. Proper error handling is essential for writing robust and reliable JavaScript code.