简体   繁体   中英

Proper throw syntax in JavaScript

If I use:

throw new Error('You broke it');

I get an output in the chrome console that looks like this: 抛出新的Error()

where it basically looks like it's doing

console.error(new Error('You broke it')) 

as opposed to

console.error('You broke it')

whereas if I use

throw 'You broke it';

I get this: 抛出字符串

which looks more like what I would expect.

Why does Chrome do this, and which way is correct?

I've always been told to use the first method, but the console output looks sloppier, though when I wrap a try catch , around the second it passes only the string as opposed to an actual Error object.

Included Firefox for reference: 在此处输入图片说明

You can throw any object you want -- that includes strings. So in that sense, there's nothing incorrect with either of your examples. However, you'll usually want to throw an Error object, in part because that gives you helpful information such as err.stack , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM