Exploring JavaScript Error Objects

Aug 8, 2024

Understanding Error Objects in JavaScript

Overview of Error Objects

  • Today's lecture focuses on error objects in JavaScript.
  • We'll cover how error objects work, how to throw custom errors, and examples of usage.

Key Concepts

  • Error Object Properties
    • name: Type of error (e.g., ReferenceError, SyntaxError)
    • message: Description of the error
    • stack: Provides a stack trace (less commonly used)

Demonstration of Error Objects

  1. Creating a New Repl
    • Project name example: 61_error_object
  2. Using Try-Catch
    • Example with an undefined variable:
      try {
          console.log(harry);
      } catch (error) {
          console.log(error.name);   // Outputs: ReferenceError
          console.log(error.message); // Outputs: "harry is not defined"
      }
      
  3. Throwing Custom Errors
    • To throw a custom error:
      throw new Error("Harry is not good");
      
    • Throwing a ReferenceError example:
      throw new ReferenceError("Harry is not good");
      

Custom Error Example with Age Validation

  1. Prompting User Input
    • Example code:
      let age = prompt("Enter your age");
      age = Number.parseInt(age);
      if (age > 120) {
          throw new Error("This is probably not true");
      }
      
  2. Error Handling
    • Use try-catch to manage errors:
      try {
          // code that may throw an error
      } catch (error) {
          console.log(error.message);
          console.log(error.stack);
      }
      

Types of Errors in JavaScript

  • Common errors include:
    • SyntaxError
    • ReferenceError
    • RangeError
    • Internal Error
  • More details can be found on MDN documentation regarding JavaScript errors.

Conclusion

  • Understanding how to handle and throw errors is crucial for robust coding in JavaScript.
  • In the next video, the topic of "clause" will be addressed, including its practical use cases.
  • If you encounter difficulties with the Replit environment, access the JavaScript playlist on Replit to find all necessary resources: replit.com/@codewithharry.

Additional Resources

  • Access the Ultimate JavaScript Course folder to clone and run examples directly.