异常处理是一种以可控的方式处理错误的机制。

11.1 Error 对象

JavaScript有一个内建的Error对象,它可以用来处理任意类型的错误(异常或预期错误)。还可以在创建Error实例的时候提供一些错误信息。

  1. const err = new Error('invalid email');
  2. function validateEmail(email) {
  3. if (email.match(/@/)) {
  4. return email;
  5. } else {
  6. return new Error(`invalid email:${email}`);
  7. }
  8. }
  9. const email = "jane@doe.com";
  10. const validatedEmail = validateEmail(email);
  11. if (validateEmail instanceof Error) {
  12. console.log(`Error:${validateEmail.message}`);
  13. } else {
  14. console.log(`Valid email:${validatedEmail}`);
  15. }

11.2使用try和catch处理异常

  1. function validateEmail(email) {
  2. if (email.match(/@/)) {
  3. return email;
  4. } else {
  5. return new Error(`invalid email:${email}`);
  6. }
  7. }
  8. const email = "jane@doe.com";
  9. try {
  10. const validatedEmail = validateEmail(email);
  11. if (validateEmail instanceof Error) {
  12. console.log(`Error:${validateEmail.message}`);
  13. } else {
  14. console.log(`Valid email:${validatedEmail}`);
  15. }
  16. } catch (err) {
  17. console.error(`Error:${err.message}`);
  18. }

11.3 try…catch… finally

不管是否发生错误,finally中的代码都会被执行

  1. try {
  2. console.log("this line is executed...");
  3. throw new Error("whoops");
  4. console.log("this line is not...");
  5. } catch (err) {
  6. console.log("there was an error...");
  7. } finally {
  8. console.log("...always executed");
  9. console.log("perform cleanup here");
  10. }