HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Errors

When executing JavaScript code, different errors can occur. Error handling allows you to test your code for errors, catch them when they happen, and handle them gracefully so your program doesn't crash.


The try...catch Statement

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

try {
  // Block of code to try
  adddlert("Welcome guest!"); // Error: adddlert is not defined
}
catch(err) {
  // Block of code to handle errors
  console.log(err.message); // Displays the error message
}

The throw Statement

The throw statement allows you to create a custom error. Technically you can throw anything (a string, a number, a boolean, or an object), but it is best practice to throw an Error object.

function checkAge(age) {
  if (age < 18) throw "Too young!";
  if (age > 100) throw new Error("Age is unrealistic");
}

The finally Statement

The finally statement defines a block of code to be executed regardless of the result (whether an error was caught or not). It is perfect for cleanup tasks like closing files or stopping loading animations.


Built-in Error Types

  • ReferenceError: Occurs when you use a variable that hasn't been declared.
  • TypeError: Occurs when you use a value that is outside the range of expected types (e.g., calling a non-function).
  • SyntaxError: Occurs when you try to interpret code with a syntax error.
  • RangeError: Occurs when a number is "out of range" (e.g., setting array length to -1).

Key Points to Remember

  • Use try to wrap risky code
  • Use catch to manage the fallout without crashing
  • throw lets you control the "bad" logic in your own app
  • finally always runs—perfect for "cleaning up"
  • The Error object provides a name and message for debugging
  • Error handling is critical for Asynchronous operations like API calls