try/catch
一句话解释
try/catch 是 construct 那个 lets 你 attempt code 那个 可能 throw 错误 and handle 它 gracefully 相反 的 crashing.
用大白话说
try/catch 是如何你 handle 错误 in JavaScript. Code in try 块运行通常. 如果它 throws 错误, execution jumps 到 catch 块使用错误对象. 如果否 错误 occurs, catch is skipped.
An optional 最后 block runs regardless of whether an error occurred — even if 返回 is called in try or catch. This makes it ideal for cleanup (closing files, releasing resources).
In async functions, try/catch catches rejected Promises when used with 等待. Without async/await, use .catch() on the Promise chain. Always handle errors to avoid unhandled rejections and crashes.
示例
javascript
try {
const data = JSON.parse("invalid json");
} catch (err) {
console.log("Parse failed:", err.message);
} finally {
console.log("Cleanup runs always");
}try 运行 code, catch handles 错误, 最后 总是 运行.
相关术语
相关资源
相关课程
- 函数
学习 关于 try/catch.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。