最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does parseFloat ever throw an error? - Stack Overflow

programmeradmin0浏览0评论

In the codebase I'm working on, I encountered code like this:

try {
    price = parseFloat(price);
} catch (err) {
    console.log(err);
}

I know that in most cases where price cannot be turned into a number, it'll simply get the value of NaN instead. My question is: are there cases where it will throw an error, making the try-catch-construction necessary?

In the codebase I'm working on, I encountered code like this:

try {
    price = parseFloat(price);
} catch (err) {
    console.log(err);
}

I know that in most cases where price cannot be turned into a number, it'll simply get the value of NaN instead. My question is: are there cases where it will throw an error, making the try-catch-construction necessary?

Share Improve this question asked Oct 31, 2016 at 10:53 Bart SBart S 1,8081 gold badge19 silver badges22 bronze badges 1
  • 1 Depends on what price is. Try with var price = {valueOf() { throw new Error; }} – Bergi Commented Oct 31, 2016 at 10:59
Add a comment  | 

3 Answers 3

Reset to default 12

are there cases where it will throw an error, making the try-catch-construction necessary?

Yes. Apart from reference errors (because price was not declared) or parseFloat was overwritten with something that's not a function or the like, the builtin parseFloat can also throw exceptions.

It does however never throw an error when you pass in a string. It will only throw when trying to convert the argument to a string fails with an exception. Examples for that include:

  • passing a symbol
  • passing an object without [Symbol.toPrimitive], .valueOf or .toString methods
  • passing an object where one of these methods throws
  • passing an object where none of these methods return a primitive

Short answer: No.

from MDN

A floating point number parsed from the given string. If the first character cannot be converted to a number, NaN is returned

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

parseFloat() itself only returns and never throws an error. However if the variable price has not been declared in the context you will get an error like:

Uncaught ReferenceError: price is not defined

It explains the reason why there is a try/catch block around it.

So to answer your question: Yes there are cases when it is necessary if you can't trust previous js execution/context (due to adblockers or similar for instance) but no it's not the function parseFloat() that throws the error it's the interpreter.

发布评论

评论列表(0)

  1. 暂无评论