try
、catch
和 finally
块用于处理异常(一种错误)。在学习它们之前,你需要了解编程中的错误类型。
错误类型
在编程中,代码可能存在两种类型的错误:
语法错误:语法错误。例如,如果你写 consol.log('your result');
,上面的程序就会抛出语法错误。上面的代码中,console
的拼写是错误的。
运行时错误:这类错误发生在程序执行期间。例如:
调用一个无效的函数或变量。
这些在运行时发生的错误称为异常。现在,让我们看看如何处理这些异常。
JavaScript try...catch 语句
try...catch
语句用于处理异常。其语法如下:
try {
// body of try
}
catch(error) {
// body of catch
}
主代码位于 try
块中。在执行 try
块时,如果发生任何错误,它会跳转到 catch
块。catch
块根据 catch 语句来处理错误。
如果没有发生错误,则执行 try
块中的代码,并且会跳过 catch
块。
示例 1:显示未声明的变量
// program to show try...catch in a program
const numerator= 100, denominator = 'a';
try {
console.log(numerator/denominator);
// forgot to define variable a
console.log(a);
}
catch(error) {
console.log('An error caught');
console.log('Error message: ' + error);
}
输出
NaN An error caught Error message: ReferenceError: a is not defined
在上面的程序中,变量 a 没有被定义。当你尝试打印变量 a 时,程序会抛出一个错误。该错误被 catch
块捕获。
JavaScript try...catch...finally 语句
你还可以使用 try...catch...finally
语句来处理异常。finally
块无论代码是否成功运行,或者是否发生错误,都会执行。
try...catch...finally
块的语法是:
try {
// try_statements
}
catch(error) {
// catch_statements
}
finally() {
// codes that gets executed anyway
}
示例 2:try...catch...finally 示例
const numerator= 100, denominator = 'a';
try {
console.log(numerator/denominator);
console.log(a);
}
catch(error) {
console.log('An error caught');
console.log('Error message: ' + error);
}
finally {
console.log('Finally will execute every time');
}
输出
NaN An error caught Error message: ReferenceError: a is not defined Finally will execute every time
在上面的程序中,发生了一个错误,该错误被 catch
块捕获。finally
块在任何情况下都会执行(无论程序是否成功运行或是否发生错误)。
注意:你需要在 try
语句之后使用 catch
或 finally
语句。否则,程序将抛出错误 Uncaught SyntaxError: Missing catch or finally after try。
JavaScript try...catch 在 setTimeout 中
如果异常发生在“定时”代码中,例如在 setTimeout() 中,try...catch
将无法捕获该异常。例如:
try {
setTimeout(function() {
// error in the code
}, 3000);
} catch (e) {
console.log( "won't work" );
}
上面的 try...catch
不会起作用,因为引擎已经离开了 try..catch
结构,函数将在稍后执行。
try..catch
块必须位于该函数内部才能捕获定时函数中的异常。例如:
setTimeout(function() {
try {
// error in the code
} catch {
console.log( "error is caught" );
}
}, 3000);
你还可以使用 throw
语句与 try...catch
语句一起使用用户定义的异常。例如,某个数字除以 0。如果你想将 Infinity
视为程序中的错误,那么你可以使用 throw
语句抛出用户定义的异常来处理该情况。
另请阅读