You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript try/catch未打印自定义错误且输出NaN的原因排查

问题原因
  • try/catch 只会捕获代码块中主动抛出的运行时异常,但parseInt()解析失败时不会抛出任何错误,只会返回特殊值NaN,因此你的代码永远不会进入catch分支,自定义的错误提示自然不会打印。
  • 控制台输出的NaN是parseInt("sflkj")的正常返回结果:parseInt的解析逻辑是从字符串首位开始逐字符匹配可识别的数字内容,你传入的字符串从第一个字符开始就没有可解析的数字片段,因此直接返回NaN(即"Not a Number",是JS中表示无效数值的特殊值)。
正确实现方式

不要依赖try/catch处理这类解析失败的场景,主动对解析结果做校验即可:

let num = "sflkj"
let thenum = parseInt(num)
if (Number.isNaN(thenum)) {
    console.log("that is not a number.")
} else {
    console.log(thenum)
}

补充说明:如果确实需要沿用try/catch的结构处理这类场景,可以在校验到NaN时手动抛出错误,才会进入catch分支:

let num = "sflkj"
try {
    let thenum = parseInt(num)
    if (Number.isNaN(thenum)) {
        throw new Error("parse failed")
    }
    console.log(thenum)
} catch (error) {
    console.log("that is not a number.")
}

内容的提问来源于stack exchange,提问作者OMEGA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 01:24:20