Error Handling
控制流与错误处理
Exception handling statements
- throw statement
- try...catch statement
throw statement
ts
// 语法
throw expression;
// 示例
throw "Error2"; // String type
throw 42; // Number type
throw true; // Boolean type
throw {
toString() {
return "I'm an object!";
},
};try...catch statement
语法:
ts
try {
// 正常执行的代码
} catch(err) {
// 出错并捕获到异常执行的代码
}示例
ts
function getMonthName(mo) {
mo--; // Adjust month number for array index (so that 0 = Jan, 11 = Dec)
const months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
if (months[mo]) {
return months[mo];
} else {
throw new Error("InvalidMonthNo"); // throw keyword is used here
}
}
try {
// statements to try
monthName = getMonthName(myMonth); // function could throw exception
} catch (e) {
monthName = "unknown";
logMyErrors(e); // pass exception object to error handler (i.e. your own function)
}The finally block
语法
ts
openMyFile();
try {
writeMyFile(theData); // This may throw an error
} catch (e) {
handleError(e); // If an error occurred, handle it
} finally {
closeMyFile(); // Always close the resource
}示例
ts
function f() {
try {
console.log(0);
throw "bogus";
} catch (e) {
console.log(1);
// This return statement is suspended
// until finally block has completed
return true;
console.log(2); // 不会执行
} finally {
console.log(3);
return false; // 会覆盖前面的 "return"
console.log(4); // 不会执行
}
// "return false" is executed now
console.log(5); // 不会执行
}
console.log(f()); // 0, 1, 3, false(finally block)return后面的语句不会执行finally代码块中的return语句会覆盖catch代码块中的语句