Open In App

JavaScript Error() constructor

Last Updated : 07 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
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

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads