
上QQ阅读APP看书,第一时间看更新
3.8 错误处理
在JavaScript中,如果一条语句报错无法运行,那么,接下来的代码也无法运行,JavaScript提供了错误处理语句来处理这个问题。
3.8.1 try…catch
try…catch用于捕获try代码块中的错误,并抛到catch中。
语法:

示例代码:

finally是一个可选的关键字,无论try在代码块中有没有捕获到错误,都会执行finally中的代码。

3.8.2 throw
throw用来创建或抛出异常(exception),抛出错误后程序将会停止执行。
语法:
throw expression;
示例代码:
throw 'empty'; console.log('empty');
我们可以结合try…catch,捕获throw抛出的错误,以避免程序停止执行,示例如下。

练习
- 自定义错误信息。