[javascript] What is the difference between `throw new Error` and `throw someObject`?

I want to write a common error handler which will catch custom errors thrown on purpose at any instance of the code.

When I did throw new Error('sample') like in the following code

try {
    throw new Error({'hehe':'haha'});
    // throw new Error('hehe');
} catch(e) {
    alert(e);
    console.log(e);
}

Log shows in Firefox as Error: [object Object] and I couldn’t parse the object.

For the second throw the log shows as: Error: hehe

Whereas when I did

try {
    throw ({'hehe':'haha'});
} catch(e) {
    alert(e);
    console.log(e);
}

the console showed as: Object { hehe="haha"} in which I was able to access the error properties.

What is the difference?

Is the difference as seen in the code? Like string will be just passed as string and object as objects but the syntax will be different?

I haven’t explored throwing error object… I had done only throwing strings.

Is there any other way than the above two mentioned methods?

The answer is


throw something works with both object and strings.But it is less supported than the other method.throw new Error("") Will only work with strings and turns objects into useless [Object obj] in the catch block.


You first mention this code:

throw new Error('sample')

and then in your first example you write:

throw new Error({'hehe':'haha'}) 

The first Error object would actually be useful, because it is expecting a string value, in this case 'sample'. The second would not because you are trying to pass an object in, and it is expecting a string, and would not display a helpful error.

The error object would have the "message" property, which would be 'sample'.


you can throw as object

throw ({message: 'This Failed'})

then for example in your try/catch

try {
//
} catch(e) {
    console.log(e); //{message: 'This Failed'}
    console.log(e.message); //This Failed
}

or just throw a string error

throw ('Your error')

try {
//
} catch(e) {
    console.log(e); //Your error
}

throw new Error //only accept a string

React behavior

Apart from the rest of the answers, I would like to show one difference in React.

If I throw a new Error() and I am in development mode, I will get an error screen and a console log. If I throw a string literal, I will only see it in the console and possibly miss it, if I am not watching the console log.

Example

Throwing an error logs into the console and shows an error screen while in development mode (the screen won't be visible in production).

throw new Error("The application could not authenticate.");

Error screen in react

Whereas the following code only logs into the console:

throw "The application could not authenticate.";

The following article perhaps goes into some more detail as to which is a better choice; throw 'An error' or throw new Error('An error'):

http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/

It suggests that the latter (new Error()) is more reliable, since browsers like Internet Explorer and Safari (unsure of versions) don't correctly report the message when using the former.

Doing so will cause an error to be thrown, but not all browsers respond the way you’d expect. Firefox, Opera, and Chrome each display an “uncaught exception” message and then include the message string. Safari and Internet Explorer simply throw an “uncaught exception” error and don’t provide the message string at all. Clearly, this is suboptimal from a debugging point of view.


TLDR: they are equivalent Error(x) === new Error(x).

// this:
const x = Error('I was created using a function call!');
????// has the same functionality as this:
const y = new Error('I was constructed via the "new" keyword!');

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

throw and throw Error will are functionally equivalent. But when you catch them and serialize them to console.log they are not serialized exactly the same way:

throw 'Parameter is not a number!';
throw new Error('Parameter is not a number!');
throw Error('Parameter is not a number!');

Console.log(e) of the above will produce 2 different results:

Parameter is not a number!
Error: Parameter is not a number!
Error: Parameter is not a number!

The Error constructor is used to create an error object. Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions.

User-defined Errors are thrown via the throw statement. program control will be passed to the first catch block in the call stack.

The difference between throwing an error with and without Error object:


throw {'hehe':'haha'};

In chrome devtools looks like this:

enter image description here

Chrome tells us that we have an uncaught error which just is a JS object. The object itself could have information regarding the error but we still don't know immediately where it came from. Not very useful when we are working on our code and debugging it.


throw new Error({'hehe':'haha'}); 

In chrome devtools looks like this:

enter image description here

An error thrown with the Error object gives us a stack trace when we expand it. This gives us valuable information where the error precisely came from which is often valuable information when debugging your code. Further note that the error says [object Object], this is because the Error constructor expects a message string as a first argument. When it receives a object it will coerce it into a string.


throw "I'm Evil"

throw will terminate the further execution & expose message string on catch the error.

_x000D_
_x000D_
try {
  throw "I'm Evil"
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e); // I'm Evil
}
_x000D_
_x000D_
_x000D_

Console after throw will never be reached cause of termination.


throw new Error("I'm Evil")

throw new Error exposes an error event with two params name & message. It also terminate further execution

_x000D_
_x000D_
try {
  throw new Error("I'm Evil")
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e.name, e.message); // Error I'm Evil
}
_x000D_
_x000D_
_x000D_

throw Error("I'm Evil")

And just for completeness, this works also, though is not technically the correct way to do it -

_x000D_
_x000D_
try {
  throw Error("I'm Evil")
  console.log("You'll never reach to me", 123465)
} catch (e) {
  console.log(e.name, e.message); // Error I'm Evil
}

console.log(typeof(new Error("hello"))) // object
console.log(typeof(Error)) // function
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to error-handling

must declare a named package eclipse because this compilation unit is associated to the named module Error:Failed to open zip file. Gradle's dependency cache may be corrupt What does 'index 0 is out of bounds for axis 0 with size 0' mean? What's the source of Error: getaddrinfo EAI_AGAIN? Error handling with try and catch in Laravel What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? Raise error in a Bash script Javascript Uncaught TypeError: Cannot read property '0' of undefined Multiple values in single-value context IndexError: too many indices for array

Examples related to exception-handling

Catching FULL exception message Spring Resttemplate exception handling How to get exception message in Python properly Spring Boot REST service exception handling java.net.BindException: Address already in use: JVM_Bind <null>:80 Python FileNotFound The process cannot access the file because it is being used by another process (File is created but contains nothing) Java 8: Lambda-Streams, Filter by Method with Exception Laravel view not found exception How to efficiently use try...catch blocks in PHP

Examples related to throw

PHP Fatal error: Uncaught exception 'Exception' continuing execution after an exception is thrown in java What is the difference between `throw new Error` and `throw someObject`? Throwing exceptions from constructors