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