Open In App

The ‘new’ operator in Javascript for Error Handling

In this article, we will see new operator usage during error throwing as well as handling the error() method in JavaScript using theoretical as well as coding examples.

JavaScript new operator: The new operator is actually a special operator that is used along with the error() method which is the method for the error class used to instantiate any specific error in order to declare any newly user-defined error. Generally, we implement these things under the try-catch block structure. We throw an error in the try block and catch that thrown error in the catch block.



Let us understand the above-said facts thoroughly with the help of certain syntaxes. The following syntax illustrates to us how to use the new operator with the error() method in order to instantiate user-defined errors.

Syntax:



new Error (error_message); 

Note: The error_message could be anything in the form of a string.

Another below-illustrated syntax illustrates how we may use the above syntax in order to throw an error.

throw new Error (error_message);  

Another syntax shown below illustrates how to implement the above two syntaxes under the try-catch block itself.

try {
    throw new Error (error_message);
} catch(error) {
    // handle this error...    
}

Example 1: 




<script>
    try {
        throw new Error("Something went wrong!!..");
    }
    catch (error) {
        console.log(error.message);
    }
</script>

Output:

Something went wrong!!..

Example 2: 




<script>
    let firstErrorThrowingFunction = () => {
        throw new Error("Something went wrong!!!....");
    };
     
    let secondErrorThrowingFunction = () => {
        throw new Error("Please try again later...!!");
    };
     
    let errorHandlerMethod = async () => {
        try {
            await firstErrorThrowingFunction();
        } catch (error) {
            console.log(error.message);
        }
     
        try {
            await secondErrorThrowingFunction();
        } catch (error) {
            console.log(error.message);
        }
    };
    errorHandlerMethod();   
</script>

Output:

Something went wrong!!!....
Please try again later...!!

Article Tags :