异常
一句话解释
异常是 错误那个 occurs 期间 program execution and 能是 caught and handled 使用 try/catch.
用大白话说
An exception is an error that happens while your program is running — like dividing by zero, accessing a null reference, or failing to open a file. Unlike syntax errors (caught before running), exceptions occur during execution and can be caught and handled gracefully.
The try/catch mechanism lets you wrap risky code: the try block runs the code, and if an exception occurs, execution jumps to the catch block where you can handle the error — log it, show a user-friendly message, or recover.
Without exception handling, an uncaught exception crashes the program. With it, you can anticipate problems and handle them gracefully. Common exceptions include TypeError, ReferenceError, RangeError in JavaScript, and ValueError, TypeError, KeyError in Python.
示例
try {
const data = JSON.parse("invalid json");
console.log(data);
} catch (error) {
console.log("Failed to parse JSON:", error.message);
}
// Output: Failed to parse JSON: Unexpected token...
// Program continues running instead of crashingJSON.parse throws 异常 on 无效输入. try/catch catches 它 and prints friendly 消息相反的 crashing.
相关术语
相关资源
相关课程
- 错误
学习关于错误 and 异常.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。