错误是反馈。高级工程师会预见错误并处理它们,确保用户永远不会看到损坏的页面。
安全网 (Try/Catch)
javascript
function riskyOperation() {
if (Math.random() > 0.5) throw new Error("服务器爆炸 💥");
return "成功!";
}
try {
console.log("尝试中...");
const result = riskyOperation();
console.log(result);
} catch (err) {
// 优雅处理
console.log("捕获到错误:", err.message);
console.log("别担心,应用还活着。");
} finally {
console.log("清理: 关闭连接...");
}'Finally' 块
finally 无论如何都会运行。无论操作成功还是失败,它都非常适合清理(隐藏加载微调器,关闭文件)。