JS Tutorial


JS ERRORS



JavaScript Errors 🚨

Errors in JavaScript are unexpected issues that occur during code execution. They can be caused by syntax mistakes, undefined variables, or logical errors in your program.

❗ Types of JavaScript Errors

  • SyntaxError: Incorrect syntax that prevents code from being parsed.
  • ReferenceError: Refers to an undefined variable.
  • TypeError: Occurs when a value is not of the expected type.
  • RangeError: A number is outside the allowable range.
  • EvalError: Improper use of eval() function (rarely used).
  • URIError: Errors in encodeURI() or decodeURI().

πŸ§ͺ Example: Trigger a TypeError

Click the button to trigger an error.

πŸ›‘οΈ Handling Errors with try...catch

You can handle errors gracefully using the try...catch block:

try {
  let x = y + 1;  // y is not defined
} catch (error) {
  console.log("Error caught:", error.message);
}

Note: try...catch only catches runtime errors, not syntax errors.

⚠️ Using finally

The finally block always runs whether an error occurred or not.

try {
  let num = 5;
  num.toUpperCase();  // TypeError
} catch (error) {
  console.log("Caught:", error.message);
} finally {
  console.log("Finally block always runs.");
}

🧨 Creating Custom Errors

You can throw custom errors using the throw statement:

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

try {
  checkAge(15);
} catch (e) {
  console.log(e.message);
}

🎯 Live Example: Custom Error


Tip: Always validate user inputs and use try...catch to prevent crashing the entire app due to one unexpected error.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review