Open In App

How to throw an error when using a property of an object ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will try to understand how we may throw an error when using a property of an object with the help of certain theoretical explanations as well as coding examples in JavaScript.

Let us first have a look over the below section which shows the syntax for creating an object having certain properties and their corresponding values in JavaScript.

Syntax:

let object_name = {
    property_name : value,
    ...
}

Now, let us have a quick look over the below example which shows the creation of an object and also how to access any property of an object in JavaScript.

Example: In this example, we will create an object which will contain simple property-value pair along with the nested object’s property-value pairs, and try to access any property from it and display it in the output.

Javascript




<script>
    let employee_details = {
        name: "Aman",
        designation: "technical writer",
        age: 22,
        graduated: true,
        address: {
            street: "XYZ",
            place: "ABC",
            state: "PQR",
            pincode: 1122333,
        },
        skills: {
            coding: ["C", "C++", "Java"],
            frontEnd_BackEnd: ["HTML", "CSS"
                "JavaScript", "React", "TypeScript"],
        },
    };
  
    console.log(employee_details);
  
    console.log(
        "Place where an employee lives is : " 
            + employee_details.address.place
    );
</script>


Output:

{
  name: 'Aman',
  designation: 'technical writer',
  age: 22,
  graduated: true,
  address: { street: 'XYZ', place: 'ABC', 
      state: 'PQR', pincode: 1122333 },
  skills: {
    coding: [ 'C', 'C++', 'Java' ],
    frontEnd_BackEnd: [ 'HTML', 'CSS', 
        'JavaScript', 'React', 'TypeScript' ]
  }
}
Place where an employee lives is : ABC

Now let us have a look over our main problem statement, which is how to throw an error when using a property of an object with the help of certain examples shown below:

Example 1: 

  • In this example, we will first create an empty object using the syntax which was shown in the previous section.
  • After creating an empty object, we will use Object.defineProperty() method with the help of which we will define a property on the same object which will further create a function that will the error.
  • In other words, we will use that method to define certain properties on any object created so far, and further, we will define any function which will perform its work when that property from that object is accessed.
  • This implies that this property is not defined and hence using that function on the same property we will generate or throw an error whenever that same property is accessed.
  • Later inside the try/catch block, we will access the property and then catch the corresponding thrown error from that function inside the catch block.

Javascript




<script>
    let employee_data = {};
    Object.defineProperty(employee_data, "name", {
        get: function () {
            throw new Error("Employee Data not found!");
        },
    });
  
    try {
        let data = employee_data.name;
        console.log(data);
    } catch (error) {
        console.log("Caught Error: " + error.message);
    }
</script>


Output:

Caught Error: Employee Data not found!

Example 2: 

  • In this example, we will create an empty object as we have created in the previous example too but here we will create it using a Proxy that will override the getter function for the user-defined methods. 
  • After defining a get function, that contains the targeted object and its property, we will throw an error inside that function which will display that property_name passed in is not found. 
  • Then using try/catch blocks we will access the properties and catch their corresponding errors in the catch block itself.

Javascript




<script>
    let employee_data = new Proxy(
        {},
        {
            get(object_name, property_name) {
                throw new Error(`${property_name} 
                    property not found!!..`);
            },
        }
    );
  
    try {
        let property_1 = employee_data.age;
        console.log(property_1);
    } catch (error) {
        console.log(error.message);
    }
  
    try {
        let property_1 = employee_data.name;
        console.log(property_1);
    } catch (error) {
        console.log(error.message);
    }
</script>


Output:

age property not found!!..
name property not found!!..

Example 3: 

  • In this example, we will create an object with certain properties and their corresponding values (in both string and number format).  
  • Then we will create a function that will accept two parameters which are the property’s name and the targeted object itself.
  • Thereafter we will check whether or not the corresponding property exists in that passed in object and according we will return true or false. 
  • Later using that returned function value we will throw an error if the property is not found in that object itself and will catch the error in the catch block itself.

Javascript




<script>
    let employee_details = {
        name: "Aman",
        age: 22,
    };
  
    let checkProperty = (propertyName, object) => {
        return propertyName in object ? true : false;
    };
  
    try {
        if (checkProperty("address", employee_details) === false)
            throw new Error("Property not found..!!");
    } catch (error) {
        console.log("Caught Error: " + error.message);
    }
</script>


Output:

Caught Error: Property not found..!!


Last Updated : 27 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads