JS 异常处理

try 语句使您能够测试代码块中的错误。
catch 语句允许您处理错误。
throw 语句允许您创建自定义错误 抛出异常(error对象包含name和message属性)。
finally 使您能够执行代码,在 try 和 catch 之后,无论结果如何。

try{
  代码块 throw xxx
}catch(err){
  处理异常
}finally{
  总是执行的代码块
}

finally 使用场景:文件操作在 finally 关闭文件

Error 对象 类型

EvalError已在 eval() 函数中发生的错误(旧版js)
RangeError数值变量或参数超出其有效范围
ReferenceError无效引用
SyntaxError语法错误
TypeError变量或参数不属于有效类型
URIError给 encodeURI() 或 decodeURI() 传递的参数无效
AggregateError由一个操作产生且需要报告的多个错误 如:Promise.any()
DOMException
DOMError

Error 实例属性方法

Error.prototype.message错误消息。对于用户创建的 Error 对象,这是构造函数的第一个参数提供的字符串。
Error.prototype.name错误名称。这是由构造函数决定的。
Error.prototype.cause (en-US)表示导致当前错误被抛出的原因——通常是另一个错误。对于用户创建的 Error 对象,这是构造函数的第二个参数提供的值。
Error.prototype.toString()返回表示该对象的字符串。覆盖了 Object.prototype.toString() 方法。
throw new Error(message, fileName, lineNumber)
class CustomError extends Error {
  constructor(foo = 'bar', ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError);
    }

    this.name = 'CustomError';
    // Custom debugging information
    this.foo = foo;
    this.date = new Date();
  }
}

try {
  throw new CustomError('baz', 'bazMessage');
}

处理未捕获异常

浏览器

window.onerror()
绑定 onerror 事件

Node.js

process.on('uncaughtException', () => {})
process.on('unhandledRejection', () => {})
posted @   海胆Sur  阅读(14)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示