Error handling is the process of managing errors
// try block contains the code that might throw an error
try {
const result = someUndefinedVariable + 10; // This line will throw an error because someUndefinedVariable is not defined
console.log(result);
} catch (error) {
// catch block is where the error is handled
console.log('An error occurred:', error.message);
}
// Output:
// An error occurred: someUndefinedVariable is not definedFinally, block is used to execute some code irrespective of error.
-
Without Exception
If there is no exception then everything runs normally under
trythen moves tofinally. -
With Exception
If there is an exception. Then
tryrun till error, thencatchruns and thenfinallyruns
try {
const result = someUndefinedVariable + 10;
console.log(result);
} catch (error) {
console.log('An error occurred:', error.message);
} finally {
console.log("finally executed");
}The throw statement stops the execution of the current function and passes the error to the catch block of the calling function.
- Method 1 (try-catch)
- Method 2 (throw)
function UserData() {
try {
validateUserAge(25);
validateUserAge("invalid"); // This will throw
validateUserAge(15); // This will not execute
} catch (error) {
console.error("Error:", error.message);
}
}
function validateUserAge(age) {
if (typeof age !== "number") {
throw new Error("Age must be a number");
}
console.log("User age is valid");
}Error propagation refers to the process of passing or propagating an error from one part of the code to another by using the throw statement with try-catch.
- Method 1 (try-catch)
- Method 2 (throw)
function UserData() {
try {
validateUserAge(25);
validateUserAge("invalid"); // This will throw
validateUserAge(15); // This will not execute
} catch (error) {
console.error("Error:", error.message);
}
}
function validateUserAge(age) {
if (typeof age !== "number") {
throw new Error("Age must be a number");
}
console.log("User age is valid");
}// 1. Use Try Catch and Handle Errors Appropriately
try {
// Code that may throw an error
} catch (error) {
// Error handling and recovery actions
}// 2. Use Descriptive Error Messages
throw new Error("Cannot divide by zero");// 3. Avoid Swallowing Errors
try {
// Code that may throw an error
} catch (error) {
// Do not leave the catch blank
}// 4. Log Errors
try {
// Code that may throw an error
} catch (error) {
console.error("An error occurred:", error);
// Log the error with a logging library
}| Error Type | Description | Example |
|---|---|---|
| SyntaxError | An error in the syntax of the JavaScript code. | console.log("Hello, World!); (Missing closing parenthesis) |
| ReferenceError | An error that occurs when a variable or object is accessed before it is declared or defined. | console.log(myVariable); (myVariable is not defined) |
| TypeError | An error that occurs when an operation is attempted on an object of an incorrect type. | const number = 42; console.log(number.toUpperCase()); (number.toUpperCase is not a function) |
| RangeError | An error that occurs when a numeric value falls outside of the allowed range for a specific operation. | const array = [1, 2, 3]; console.log(array[10]); (Index 10 is out of bounds) |
// Syntax Error
console.log("Hello, World!");
// Missing closing parenthesis );
// Reference Error
console.log(myVariable);
// myVariable is not defined
// Type Error
const number = 42;
console.log(number.toUpperCase());
// number.toUpperCase is not a function
// Range Error
const array = [1, 2, 3];
console.log(array[10]);
// Index 10 is out of bounds