JavaScript例外

When the code runs into an unexpected problem, the JavaScript idiomatic way to handle this situation is through exceptions.

当代码遇到意外问题时,JavaScript惯用的方式是通过异常来处理这种情况。

创建例外 (Creating exceptions)

An exception is created using the throw keyword:

使用throw关键字创建一个异常:

throw value

where value can be any JavaScript value including a string, a number or an object.

其中value可以是任何JavaScript值,包括字符串,数字或对象。

As soon as JavaScript executes this line, the normal program flow is halted and the control is held back to the nearest exception handler.

JavaScript一旦执行此行,就会停止常规程序流,并将控件保留到最近的异常处理程序

处理异常 (Handling exceptions)

An exception handler is a try/catch statement.

异常处理程序是try / catch语句。

Any exception raised in the lines of code included in the try block is handled in the corresponding catch block:

try块中包含的代码行中引发的任何异常都在相应的catch块中处理:

try {
  //lines of code
} catch (e) {

}

e in this example is the exception value.

在此示例中, e是异常值。

You can add multiple handlers, that can catch different kinds of errors.

您可以添加多个处理程序,它们可以捕获各种错误。

finally (finally)

To complete this statement JavaScript has another statement called finally, which contains code that is executed regardless of the program flow, if the exception was handled or not, if there was an exception or if there wasn’t:

为了完成此语句,JavaScript还有另一个名为finally语句,该语句包含无论程序流程如何,是否处理了异常,是否存在异常或是否没有异常,都将执行的代码:

try {
  //lines of code
} catch (e) {

} finally {

}

You can use finally without a catch block, to serve as a way to clean up any resource you might have opened in the try block, like files or network requests:

您可以finally使用没有catch块的方法,以作为清理可能在try块中打开的任何资源的方法,例如文件或网络请求:

try {
  //lines of code
} finally {

}

嵌套try(Nested try blocks)

try blocks can be nested, and an exception is always handled in the nearest catch block:

可以嵌套try块,并且总是在最近的catch块中处理异常:

try {
  //lines of code

  try {
    //other lines of code
  } finally {
    //other lines of code
  }

} catch (e) {

}

If an exception is raised in the inner try, it’s handled in the outer catch block.

如果内部try引发异常,则在外部catch块中处理该异常。

翻译自: https://flaviocopes.com/javascript-exceptions/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值