Skip to content

异常 / try catch

https://www.yuque.com/qinsjs/jsinfo/kvkewb

发生错误,脚本就会“死亡”(立即停止)

try...catch 只能处理 “运行时的错误(runtime errors)”,有时被称为“异常(exceptions)”

基础款

js
function func() {
  try {
    return 1;
  } catch (e) {
    console.error("error");
  } finally {
    console.log("finally");
  }
}

console.log(func());

// finally
// 1

no catch

需要 polyfills

js
try {
  // ...
} catch {
  // 没有 (err)
}

scheduled

try catch 无法捕获 scheduled

js
try {
  setTimeout(function () {
    noSuchVariable; // 脚本将在这里停止运行
  }, 1000);
} catch (err) {
  alert("不工作");
}

抛出异常

js
throw new SyntaxError("Incomplete data: no name");
throw new Error("message");
throw new ReferenceError("message");

再次抛出(Rethrowing)

无法处理的 Error 应该再次抛出,即 throw e

Error 对象

内建的 error 对象具有两个主要属性:

  • name:Error 名称。
  • message:关于 error 的详细文字描述。
  • stack:当前的调用栈。非标准属性,但大多数环境中可用。

自定义 Error 对象

todo

全局 catch

浏览器中有 window.onerror
https://developer.mozilla.org/zh-CN/docs/Web/API/Window/error_event

Node.JS 有 process.on("uncaughtException")
https://nodejs.org/api/process.html#process_event_uncaughtexception
https://nodejs.cn/api/process.html#process_event_uncaughtexception

浏览器

js
window.onerror = function (msg, url, lineNo, columnNo, error) {};

addEventListener 的 信息都在 event 中

js
window.addEventListener("error", (event) => {});