JavaScript Errors And Exception Handling With Examples

Errors are common in JavaScript. Exception handling allows you to catch and handle errors gracefully, preventing your application from crashing. The try, catch, and finally statements are used for this purpose.

This blog explains different types of errors and how to handle them.


1. Common JavaScript Errors

1. Syntax Error

Occurs when code is not written correctly.

// console.log("Hello World" // Missing closing parenthesis

2. Reference Error

Occurs when referring to a variable that does not exist.

console.log(myVar); // ReferenceError: myVar is not defined

3. Type Error

Occurs when a value is of unexpected type.

let num = 5;
num.toUpperCase(); // TypeError: num.toUpperCase is not a function

4. Range Error

Occurs when a number is out of allowed range.

let num = 1;
num.toPrecision(500); // RangeError

2. Try and Catch

Use try to execute code and catch to handle errors.

try {
  let result = riskyFunction();
} catch (error) {
  console.log("An error occurred: " + error.message);
}

3. Finally Block

The finally block runs regardless of whether an error occurs.

try {
  console.log("Try block runs");
  throw new Error("Oops!");
} catch (error) {
  console.log("Catch block: " + error.message);
} finally {
  console.log("Finally block runs always");
}

Output:

Try block runs
Catch block: Oops!
Finally block runs always

4. Throwing Custom Errors

You can create your own errors using throw.

function checkAge(age) {
  if(age < 18) {
    throw new Error("You must be 18 or older");
  }
  return true;
}

try {
  checkAge(15);
} catch (error) {
  console.log(error.message); // You must be 18 or older
}

5. Why Exception Handling Matters

  • Prevents application crashes
  • Helps debug and log errors
  • Handles unexpected situations gracefully
  • Improves user experience

Conclusion

Exception handling in JavaScript is essential for robust and reliable code. Using try, catch, finally, and custom errors allows developers to anticipate problems and respond appropriately without breaking the application.


📌 Citations

🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/

🔗 External Javascript Documentation:
https://www.w3schools.com/js/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *