js 异常处理

throw:

语法:throw expression;

expression may evaluate to a value of any type.

(expression 的值可以是任何类型的)

 Commonly, however, it is an Error object or an instance of one of the subclasses of Error. It can also be useful to throw a string that contains an error message, or a numeric value that represents some sort of error code.

 

function factorial(x) {
    // If the input argument is invalid, throw an exception!
    if (x < 0) throw new Error("x must not be negative");
    // Otherwise, compute a value and return normally
    for(var f = 1; x > 1; f *= x, x--) /* empty */ ;
    return f;
}

 

try catch finally

try {
  // Normally, this code runs from the top of the block to the bottom (通常,代码会从顶部运行到底部)
  // without problems. But it can sometimes throw an exception, 

  // either directly, with a throw statement, or indirectly, by calling(可以直接用throw语句或通过调用一个抛出异常的方法间接的 抛出异常)
  // a method that throws an exception.
}
catch (e) {
  // The statements in this block are executed if, and only if, the try
  // block throws an exception. These statements can use the local variable
  // e to refer to the Error object or other value that was thrown.
  // This block may handle the exception somehow, may ignore the
  // exception by doing nothing, or may rethrow the exception with throw.
}
finally {
  // This block contains statements that are always executed, regardless of
  // what happens in the try block. They are executed whether the try
  // block terminates:
  //   1) normally, after reaching the bottom of the block
  //   2) because of a break, continue, or return statement
  //   3) with an exception that is handled by a catch clause above
  //   4) with an uncaught exception that is still propagating
}

 如果finally块自身用return语句、continue语句、break语句或throw语句转移了控制流、或者调用了抛出异常的方法改变了控制流,那么等待的控制流转移将被舍弃,并进行了新的转移,例如:若finally从句抛出了一个异常,那么该异常将代替处于抛出过程中的异常。如果finally从句用到了return语句,那么即使已经抛出了一个异常,而且该异常还没有被处理,该方法也会正常返回。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值