每当 JavaScript 中发生任何运行时错误时,都会引发Error
对象。 在许多情况下,我们还可以扩展这些标准Error
对象,以创建我们自己的自定义Error
对象。
属性
Error
对象具有2个属性
name ——设置或返回错误名称。具体来说,它返回错误所属的构造函数的名称。
它有6个不同的值-EvalError
,RangeError
,ReferenceError
,TypeError
,SyntaxError
,URIError
。 我们将在本文后面讨论这些内容,这些所有错误类型均继承自Object-> Error-> RangeError
。
message-设置或返回错误消息
事例
1.通用的错误
我们可以使用Error
对象创建一个新的Error
,然后使用throw
关键字显式抛出该错误。
try{ throw new Error('Some Error Occurred!') } catch(e){ console.error('Error Occurred. ' + e.name + ': ' + e.message) }
2.处理特定的错误类型
我们还可以使用如下的instanceof
关键字来处理特定的错误类型。
try{ someFunction() } catch(e){ if(e instanceof EvalError) { console.error(e.name + ': ' + e.message) } else if(e instanceof RangeError) { console.error(e.name + ': ' + e.message) } // ... something else }
3.自定义错误类型
我们还可以通过创建继承Error
对象的类来定义自己的错误类型。
class CustomError extends Error { constructor(description, ...params) { super(...params) if(Error.captureStackTrace){ Error.captureStackTrace(this, CustomError) } this.name = 'CustomError_MyError' this.description = description this.date = new Date() } } try{ throw new CustomError('Custom Error', 'Some Error Occurred') } catch(e){ console.error(e.name) //CustomError_MyError console.error(e.description) //Custom Error console.error(e.message) //Some Error Occurred console.error(e.stack) //stacktrace }
浏览器兼容性
Error 的对象类型
现在让我们讨论可用于处理不同错误的不同错误对象类型。
1. EvalError
创建一个error
实例,表示错误的原因:与 eval()
有关。
这里要注意的一点是,当前ECMAScript规范不支持它,并且运行时不会将其抛出。 取而代之的是,我们可以使用SyntaxError
错误。但是,它仍然可以与ECMAScript的早期版本向后兼容。
语法
new EvalError([message[, fileName[, lineNumber]]])
事例
try{ throw new EvalError('Eval Error Occurred'); } catch(e){ console.log(e instanceof EvalError); // true console.log(e.message); // "Eval Error Occurred" console.log(e.name); // "EvalError" console.log(e.stack); // "EvalError: Eval Error Occurred..." }
浏览器兼容性
2. RangeError
创建一个error
实例,表示错误的原因:数值变量或参数超出其有效范围。
new RangeError([message[, fileName[, lineNumber]]])
下面的情况会触发该错误:
1)根据String.prototype.normalize()
,我们传递了一个不允许的字符串值。
// Uncaught RangeError: The normalization form should be one of NFC, NFD, NFKC, NFKD String.prototype.normalize(“-1”)
2)使用Array
构造函数创建非法长度的数组
// RangeError: Invalid array length var arr = new Array(-1);
3)诸如 Number.prototype.toExponential()
,Number.prototype.toFixed()
或Number.prototype.toPrecision()
之类的数字方法会接收无效值。
// Uncaught RangeError: toExponential() argument must be between 0 and 100 Number.prototype.toExponential(101) // Uncaught RangeError: toFixed() digits argument must be between 0 and 100 Number.prototype.toFixed(-1) // Uncaught RangeError: toPrecision() argument must be between 1 and 100 Number.prototype.toPrecision(101)
事例
对于数值
function checkRange(n) { if( !(n >= 0 && n <= 100) ) { throw new RangeError("The argument must be between 0 and 100."); } }; try { checkRange(101); } catch(error) { if (error instanceof RangeError) { console.log(error.name); console.log(error.message); } }
对于非数值
function checkJusticeLeaque(value) { if(["batman", "superman", "flash"].includes(value) === false) { throw new RangeError('The hero must be in Justice Leaque...'); } } try { checkJusticeLeaque("wolverine"); } catch(error) { if(error instanceof RangeError) { console.log(error.name); console.log(error.message); } }
浏览器兼容性
3. ReferenceError
创建一个error
实例,表示错误的原因:无效引用。
new ReferenceError([message[, fileName[, lineNumber]]])
事例
ReferenceError
被自动触发。
try { callJusticeLeaque(); } catch(e){ console.log(e instanceof ReferenceError) // true console.log(e.message) // callJusticeLeaque is not defined console.log(e.name) // "ReferenceError" console.log(e.stack) // ReferenceError: callJusticeLeaque is not defined.. } or as simple as a/10;
显式抛出ReferenceError
try { throw new ReferenceError('Reference Error Occurred') } catch(e){ console.log(e instanceof ReferenceError) // true console.log(e.message) // Reference Error Occurred console.log(e.name) // "ReferenceError" console.log(e.stack) // ReferenceError: Reference Error Occurred. }
浏览器兼容性
4. SyntaxError
创建一个error实例,表示错误的原因:eval()在解析代码的过程中发生的语法错误。
换句话说,当 JS 引擎在解析代码时遇到不符合语言语法的令牌或令牌顺序时,将抛出SyntaxError
。
捕获语法错误
try { eval('Justice Leaque'); } catch(e){ console.error(e instanceof SyntaxError); // true console.error(e.message); // Unexpected identifier console.error(e.name); // SyntaxError console.error(e.stack); // SyntaxError: Unexpected identifier } let a = 100/; // Uncaught SyntaxError: Unexpected token ';' // Uncaught SyntaxError: Unexpected token ] in JSON JSON.parse('[1, 2, 3, 4,]'); // Uncaught SyntaxError: Unexpected token } in JSON JSON.parse('{"aa": 11,}');
创建一个SyntaxError
try { throw new SyntaxError('Syntax Error Occurred'); } catch(e){ console.error(e instanceof SyntaxError); // true console.error(e.message); // Syntax Error Occurred console.error(e.name); // SyntaxError console.error(e.stack); // SyntaxError: Syntax Error Occurred }
浏览器兼容性
5. TypeError
创建一个error实例,表示错误的原因:变量或参数不属于有效类型。
new TypeError([message[, fileName[, lineNumber]]])
下面情况会引发 TypeError
:
- 在传递和预期的函数的参数或操作数之间存在类型不兼容。
- 试图更新无法更改的值。
- 值使用不当。
例如:
const a = 10; a = "string"; // Uncaught TypeError: Assignment to constant variable null.name // Uncaught TypeError: Cannot read property 'name' of null
捕获TypeError
try { var num = 1; num.toUpperCase(); } catch(e){ console.log(e instanceof TypeError) // true console.log(e.message) // num.toUpperCase is not a function console.log(e.name) // "TypeError" console.log(e.stack) // TypeError: num.toUpperCase is not a function }
创建 TypeError
try { throw new TypeError('TypeError Occurred') } catch(e){ console.log(e instanceof TypeError) // true console.log(e.message) // TypeError Occurred console.log(e.name) // TypeError console.log(e.stack) // TypeError: TypeError Occurred }
浏览器兼容性
6. URIError
创建一个error实例,表示错误的原因:给 encodeURI(
)或 decodeURl()
传递的参数无效。
如果未正确使用全局URI处理功能,则会发生这种情况。
简单来说,当我们将不正确的参数传递给encodeURIComponent()或
decodeURIComponent()函数时,就会引发这种情况。
new URIError([message[, fileName[, lineNumber]]])
encodeURIComponent()
通过用表示字符的UTF-8编码的一个,两个,三个或四个转义序列替换某些字符的每个实例来对URI进行编码。
// "https%3A%2F%2Fmedium.com%2F" encodeURIComponent('https://medium.com/');
decodeURIComponent()
——对之前由encodeURIComponent
创建的统一资源标识符(Uniform Resource Identifier, URI)组件进行解码。
// https://medium.com/ decodeURIComponent("https%3A%2F%2Fmedium.com%2F")
捕捉URIError
try { decodeURIComponent('%') } catch (e) { console.log(e instanceof URIError) // true console.log(e.message) // URI malformed console.log(e.name) // URIError console.log(e.stack) // URIError: URI malformed... }
显式抛出URIError
try { throw new URIError('URIError Occurred') } catch (e) { console.log(e instanceof URIError) // true console.log(e.message) // URIError Occurred console.log(e.name) // "URIError" console.log(e.stack) // URIError: URIError Occurred.... }
浏览器兼容性
英文原文地址:http://help.dottoro.com/ljfhismo.php
作者:Isha Jauhari
更多编程相关知识,请访问:编程视频!!
以上是JavaScript中的错误对象(Error object)的详细内容。更多信息请关注PHP中文网其他相关文章!

JavaScript是现代网站的核心,因为它增强了网页的交互性和动态性。1)它允许在不刷新页面的情况下改变内容,2)通过DOMAPI操作网页,3)支持复杂的交互效果如动画和拖放,4)优化性能和最佳实践提高用户体验。

C 和JavaScript通过WebAssembly实现互操作性。1)C 代码编译成WebAssembly模块,引入到JavaScript环境中,增强计算能力。2)在游戏开发中,C 处理物理引擎和图形渲染,JavaScript负责游戏逻辑和用户界面。

JavaScript在网站、移动应用、桌面应用和服务器端编程中均有广泛应用。1)在网站开发中,JavaScript与HTML、CSS一起操作DOM,实现动态效果,并支持如jQuery、React等框架。2)通过ReactNative和Ionic,JavaScript用于开发跨平台移动应用。3)Electron框架使JavaScript能构建桌面应用。4)Node.js让JavaScript在服务器端运行,支持高并发请求。

Python更适合数据科学和自动化,JavaScript更适合前端和全栈开发。1.Python在数据科学和机器学习中表现出色,使用NumPy、Pandas等库进行数据处理和建模。2.Python在自动化和脚本编写方面简洁高效。3.JavaScript在前端开发中不可或缺,用于构建动态网页和单页面应用。4.JavaScript通过Node.js在后端开发中发挥作用,支持全栈开发。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

Atom编辑器mac版下载
最流行的的开源编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3汉化版
中文版,非常好用

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。