JavaScript try...catch 异常处理语句

79 阅读1分钟

你可以用 throw 语句抛出一个异常并且用 try...catch 语句处理它。 try...catch 语句用于标记一段要尝试的语句块,并指定抛出异常时的一个或多个响应。如果抛出了异常,try...catch 语句会捕获它。

示例
try {
  // 要尝试的语句
} catch (e) {
  // 将异常对象传递给错误处理器(例如,你写的函数)
}
throw 语句

使用 throw 语句抛出异常。throw 语句会指明要抛出的值:

try {
  // 抛出异常
  throw "错误";
} catch (e) {
  // 将异常对象传递给错误处理器(例如,你写的函数)
}

你可以抛出任意表达式而不是特定类型的表达式。下面的代码抛出了几个不同类型的异常:

throw "错误 2"; // 字符串类型
throw 42; // 数字类型
throw true; // 布尔类型
throw {
  toString() {
    return "我是一个对象";
  },
};
catch 块

你可以使用 catch 块来处理所有可能在 try 块中产生的异常。

try {
  // 抛出异常
  throw "错误";
} catch (e) {
  // 处理异常
  console.error('e');
}
finally 块

finally 块包含的语句在 try 和 catch 块执行之后执行。此外,finally 块在 try…catch…finally 语句后面的代码之前执行。同时注意,finally 块无论是否抛出异常都会执行。

try {
  // 抛出异常
  throw "错误";
} catch (e) {
  // 处理异常
  console.error('e');
} finally {
  // 无论是否抛出异常都会执行
  console.log('继续执行')
}