JavaScript constructor is a function that creates and initializes an object instance of a class. Constructors are used to create new objects and set values for existing object properties. The Error() constructor in JavaScript is used to create a new error object. An error object is thrown when a runtime error occurs. Error The object can also be used as the base object for user-defined exceptions. See below for the standard built-in error types.
The following is the syntax of the Error() constructor -
new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber)
Error() The constructor can be defined with different parameters, each Each parameter has its own meaning, as defined below -
Options - It is an optional parameter that indicates the attribute of the specific reason why the error occurred. When catching and rethrowing an error with a more specific or useful error message, this attribute should be used to pass the original error.
fileName - It is an optional parameter that has the value of the fileName property on the Error object being created. If no name is provided, fileName is equal to the name of the file containing the code called the Error() constructor.
lineNumber - It is an optional parameter The value of the lineNumber property on the created Error object. If no number is provided, lineNumber is equal to the line number containing the Error() constructor.
We can use two options to create an error object, one of which is one is to use function call and the other is to use the new key Character.
// Using Function Call const x = Error(''This error constructor is created using function call!') // Using new Keyword const y = new Error(''This object is created using "new" keyword!')
We use Error just like we would a function without the new keyword. When Error is used as a function, it returns an error object that is identical to the one created using the new keyword. We can create an error object through a function call using the following program. In this program, we create an error object and throw it using throw keyword
<html> <body> <h3> Create Error Using Function Call</h3> <p id = "result"> </p> <script> const err = Error("This error is created using function call"); try{ throw err; } catch(e){ document.getElementById("result").innerHTML = e; } </script> </body> </html>
We can use keyword " new" creates an error object. We can create an error object using the new keyword using the following program. We use try…catch and throw to throw errors.
<html> <body> <p id = "result"> </p> <script> const err = new Error("This error object is created using new keyword"); try{ throw err; } catch(e){ document.getElementById("result").innerHTML = e; } </script> </body> </html>
The above is the detailed content of What is JavaScript error constructor?. For more information, please follow other related articles on the PHP Chinese website!