Back

javascript - throw的基本用法 跟ruby 一样,不需要return

发布时间: 2022-07-09 00:26:00

跟ruby 的raise 一样。

ruby: 

raise "I got an error"

js:

throw " I got an error"

就可以了。

完整例子:

源代码:
function devide(a,b){
  if(b == 0){
    throw "b should not be 0"
  }
  return a / b
}

console.info("== 10/5: ", devide(10,5))  // 会正常运行
console.info("== 3/0:  ", devide(3,0))    // 会抛出异常,终止程序
console.info("== 3/1:  ", devide(3,1))    // 不会被运行

运行结果:

$ node test_throw.js

== 10/5:  2

/mnt/d/workspace/test_erc_721_in_truffle/test_throw.js:4
    throw "b should not be 0"
    ^
b should not be 0
(Use `node --trace-uncaught ...` to show where the exception was thrown)

是否需要return

一般是不需要的。

除非在某些特定框架下(例如truffle,  ) 需要手动终止  ( return 或者在程序中做判断 )

进一步看结果:

Back