The Wayback Machine - https://web.archive.org/web/20240204103758/https://www.geeksforgeeks.org/javascript-error-constructor/
Open In App
Related Articles

JavaScript Error() constructor

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Javascript Error() constructor is used to create a new error object. Error objects are arising at runtime errors. The error object also uses as the base object for the exceptions defined by the user.

Syntax:

new Error([message[, fileName[, lineNumber]]])

Parameters:

  • message: It contains information about this error object which is in human-readable form. An error message can be set using javascript Error message property. It is an optional parameter.
  • fileName: It is the name of the file for this error object. If no name is provided than fileName is equal to the name of file containing the code that called the Error() constructor. It is an optional parameter.
  • lineNumber: It is the value for the lineNumber property on the created Error object. If no number is provided Than the lineNumber is equal to the line number containing the Error() constructor invocation. It is an optional parameter.

Example 1: Creating error object using new keyword.

Javascript




<script>
try {
    const error = new Error('This object is created using new keyword')
    document.write("Error object created successfully using new keyword");
}
 catch(err) {
     document.write(err.message);
}
</script>


Output:

Error object created successfully using new keyword

Example 2: Creating error object using function call.

Javascript




<script>
try {
    const error =  Error('This is created is using function call')
    document.write("Error object created successfully using function call");
}
 catch(err) {
     document.write(err.message);
}
</script>


Output:

Error object created successfully using function call

Supported Browsers:

  • Google Chrome
  • Firefox
  • Edge
  • Internet Explorer
  • Opera
  • Safari

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!


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