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
块中处理该异常。