11.1 Error 对象
JavaScript有一个内建的Error对象,它可以用来处理任意类型的错误(异常或预期错误)。还可以在创建Error实例的时候提供一些错误信息。
const err = new Error('invalid email');
function validateEmail(email) {
if (email.match(/@/)) {
return email;
} else {
return new Error(`invalid email:${email}`);
}
}
const email = "jane@doe.com";
const validatedEmail = validateEmail(email);
if (validateEmail instanceof Error) {
console.log(`Error:${validateEmail.message}`);
} else {
console.log(`Valid email:${validatedEmail}`);
}
11.2使用try和catch处理异常
function validateEmail(email) {
if (email.match(/@/)) {
return email;
} else {
return new Error(`invalid email:${email}`);
}
}
const email = "jane@doe.com";
try {
const validatedEmail = validateEmail(email);
if (validateEmail instanceof Error) {
console.log(`Error:${validateEmail.message}`);
} else {
console.log(`Valid email:${validatedEmail}`);
}
} catch (err) {
console.error(`Error:${err.message}`);
}
11.3 try…catch… finally
不管是否发生错误,finally中的代码都会被执行
try {
console.log("this line is executed...");
throw new Error("whoops");
console.log("this line is not...");
} catch (err) {
console.log("there was an error...");
} finally {
console.log("...always executed");
console.log("perform cleanup here");
}