The try...catch..finally
statement specifies a block of code to try along with a response should an error occur. The try
statement contains one or more try
blocks, and ends with at least one catch
and/or a finally
clause.
try...catch..finally
语句指定代码块,以在发生错误时尝试与响应一起使用。 try
语句包含一个或多个try
块,并以至少一个catch
和/或finally
子句结尾。
try...catch
: (try...catch
:)
try {
throw new Error('my error');
} catch (err) {
console.error(err.message);
}
// Output: my error
try...finally
: (try...finally
:)
try {
throw new Error('my error');
} finally {
console.error('finally');
}
// Output: finally
When you don't use a catch
statement, the error is not "caught", even though the code in the finally
block is executed. Instead, the error will continue to the upper try
block (or main block).
当您不使用catch
语句时,即使执行了finally
块中的代码,也不会“捕获”该错误。 而是,错误将继续到上部try
块(或主块)。
try...catch...finally
: (try...catch...finally
:)
try {
throw new Error('my error');
} catch (err) {
console.error(err.message);
} finally {
console.error('finally');
}
// Output:
// my error
// finally
Typical usage:
典型用法:
try {
openFile(file);
readFile(file)
} catch (err) {
console.error(err.message);
} finally {
closeFile(file);
}
嵌套try...catch
: (Nested try...catch
:)
You can also:
你也可以:
Nest a
try-catch
statement inside atry
block.将
try-catch
语句嵌套在try
块内。
You can nest a try...catch
statement within a try
block. For example, to throw an error upwards:
您可以在try
块中嵌套try...catch
语句。 例如,向上抛出错误:
try {
try {
throw new Error('my error');
} catch (err) {
console.error('inner', err.message);
throw err;
} finally {
console.log('inner finally');
}
} catch (err) {
console.error('outer', err.message);
}
// Output:
// inner my error
// inner finally
// outer my error
翻译自: https://www.freecodecamp.org/news/error-handling-and-try-catch-throw/