The throw statement allows you to create an exception or a custom error. The exception can be like a Javascript string, a number, a boolean, or an object. So, If you use this statement together with the try…catch statement. It allows you to control the flow of the program and generate accurate error messages. For example: throw “too small” (throw a text), throw 500 (throw a number), etc.
First of all, throw Error() and throw new Error() are functionally equivalent.
Syntax:
throw Error("Enter your error message here");
Error object: An object containing the error information is generated and passed to catch as an argument. Error object has three properties: name, message, and stack.
Error() constructor is used to create a new error object.
Example: For better understanding, we will take an example:
Javascript
// throw Error() try { throw Error( "msg" ); } catch (e) { console.log( "for Error()" ); console.log(e); } |
Output:
In the above code, I added a try…catch statement with having throw Error(). This code will do that the ‘msg’ error is thrown in the try-block which will be get executed by catch statements.
new Error object: It captures several properties of the place where the error happened. It exposes an error event with two parameters name & message. It also terminates further execution.
Example: For better understanding, we will take an example:
Javascript
// throw new Error() try { throw new Error( "msg" ); } catch (e) { console.log( "for new Error()" ); console.log(e); } |
Output :
In the above code, I added a try…catch statement with having throw new Error(). This code will do that the ‘msg’ error is thrown in the try-block which will be get executed by catch statements.
As you can see in the images of both of the consoles, throw an error(‘msg’) and throw a new error(‘msg’) give the same results.
Note: Error() and new Error() returns an object as a result.
Difference between throw Error() and throw new Error():
throw Error() |
throw new Error() |
Error(…) is less reliable and consistent. | new Error(…) is more reliable and consistent. |
the Error object contains a stack trace and other useful debugging information which is lost when you use a string literal. | Creating objects using ES6 classes requires the use of new and extending Error via a class is the only way to preserve stack traces. |
We can create an exception or a custom error using throw Error() | The new Error() method is an inbuilt application programming interface of the Node module |
throw Error() is like a Javascript string, a number, a boolean, or an object. | It returns specific errors as defined in the message value which is passed as an argument. |
We can control the flow of the program and generate accurate error messages using throw Error() | It Creates a new Error object and sets the error.message property to the provided text message. |
The throw statement throws an exception. |
Its syntax is -: new Error(message) |