Introduction to JavaScript error handling mechanism (with examples)
This article brings you an introduction to the JavaScript error handling mechanism (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Sometimes, in the tool function that you encapsulate, if no parameters are passed or parameters of the wrong type are passed in, some errors should be thrown as a warning; it will also be thrown if the framework is not used normally. If something goes wrong, if you don't know anything about the error, you won't be able to debug it. Based on the above, it is necessary to understand the error handling mechanism.
The following is the author's summary. If there are any errors, please point them out.Error constructor
There are a total of 8 error type constructors in the JavaScript specification
Error -- error object
SyntaxError --parsing process syntax error
TypeError --not valid Type
ReferenceError -- Invalid reference
RangeError -- The value exceeds the valid range
URIError -- Error in parsing URI encoding
EvalError -- Error in calling eval function
InternalError -- Javascript engine internal error Exception thrown, "Too much recursion"
Two of them are specially explained:
EvalError is an error in calling the eval function and has been deprecated. For backward compatibility, lower versions can still be used.
InternalError throws an error if the recursion is too deep. Most browsers have not implemented it. It is a non-standard method and is disabled in the production environment.
Inheritance relationship
Error is the base class of errors. Other types inherit the Error class and can be used. Object.getPrototypeOf() provided in ES6 to determine whether a class inherits another class.
console.log(Object.getPrototypeOf(SyntaxError) === Error); // true console.log(Object.getPrototypeOf(TypeError) === Error); // true console.log(Object.getPrototypeOf(RangeError) === Error); // true console.log(Object.getPrototypeOf(URIError) === Error); // true console.log(Object.getPrototypeOf(EvalError) === Error); // true console.log(Object.getPrototypeOf(ReferenceError) === Error); // true
Let’s talk about the use of each error type and the error scenarios.
Error
An error object can be created through the Error constructor. When a runtime error occurs, an Error instance object will be thrown.
Syntax: new Error([message])
Parameters:
message 可选,错误描述信息。
Throw an error
Use the throw statement to throw an exception
throw new Error('What is thrown here is Error message')
After running, it will be printed on the console:
Uncaught Error: The error message is thrown here
Note: After using throw to throw an exception, the subsequent code will no longer be executed.
Capturing errors
You can capture this error through the try{}catch(){} statement
try{ throw new Error('这里抛出的是错误信息') } catch(err){ alert(err.name + ' '+ err.message) }
Attribute description:
当使用new Error创建错误实例后,会有两个属性:
let e = new Error('What is thrown here is the error message');
name attribute is the type of error, this time it is Error
message attribute, which is the error message, this time it is 'thrown here' The error message is '
SyntaxError
Syntax error in the parsing process. There are many errors thrown by this type, which are often grammatical errors caused when writing, for example:
let n = 11; // Uncaught SyntaxError: Invalid or unexpected token let str = "hel"lo" // Uncaught SyntaxError: Unexpected identifier let 123Var = 'hi' // Uncaught SyntaxError: Invalid or unexpected token
There are many syntax errors, so I won’t list them one by one. When running in the browser, the console will throw an error and tell you which line it is, so it is more convenient for the debugger to use it. But you need to understand the error type as SyntaxError and the error message that follows, so that you can easily correct the error.
TypeError
is not a valid type. This kind of error means that the type given is not the required type, resulting in inoperability and a type error will be thrown.
The variable or parameter is not of the expected type,
The variable or parameter is not of the expected type
For example, new must be followed by a function, and the given one is not a function, a type error will be thrown
let fn = 'hello'; new fn;
Throws an error:
Uncaught TypeError: fn is not a constructor
Calling a method that does not exist on an object
let obj = {}; obj.fn()
Throws an error:
Uncaught TypeError: obj.fn is not a function
Of course, you can also force the incoming parameters to be specified types when encapsulating the function, otherwise a type error will be thrown.
function flatten(arr){ if( !Array.isArray(arr) ) { throw new TypeError('传入参数不是数组') } }
flatten('test');
When the incoming parameter is not an array, a custom type error is thrown:
Uncaught TypeError: The incoming parameter is not an array
ReferenceError
Invalid reference.
References a variable that does not exist
console.log(a);
Throws an error
Uncaught ReferenceError: a is not defined
Assign a variable to a data that cannot be assigned a value
This mistake is often made when making a judgment in the if statement after calling a method. The comparison operator == is written as the assignment operator =. For example, judging whether the first character of a string is the specified character:
let str = 'hello'; if( str.charAt(0) = 'h' ){ console.log('第一个字符为h'); }
Throws error:
Uncaught ReferenceError: Invalid left-hand side in assignment
RangeError
The value is outside the valid range. In some methods, the value passed in must be within a certain range, otherwise an out-of-range error will be thrown.
The length passed in when creating the array is less than 0
let arr = new Array(-1)
Throws an error:
Uncaught RangeError: Invalid array length
The repeat method repeats the specified string the number of times it is repeated is less than 0
let str = 'hello'; str.repeat(-1)
Throws error:
Uncaught RangeError: Invalid count value
URIError
Error in processing URI encoding. The function parameters are incorrect, mainly the six functions encodeURI(), decodeURI(), encodeURIComponent(), decodeURIComponent(), escape() and unescape().
For example:
decodeURIComponent('%'); decodeURI('%2')
Throws an error:
Uncaught URIError: URI malformed
Custom error type
Sometimes you want to customize the error type , you need to customize a constructor, and then let the prototype inherit Error.prototype.
function MyErrorType(message){ this.message = message || '错误'; this.name = 'MyErrorType'; this.stack = (new Error()).stack; // 错误位置和调用栈 } MyErrorType.prototype = Object.create(Error.prototype); MyErrorType.prototype.constructor = MyErrorType; throw new MyErrorType('自定义错误类型抛出错误')
关于调用的错误栈信息
提供的错误的跟踪功能,以什么样的调用顺序,在哪个文件的哪一行捕获到这个错误。
例如以下调用:
function trace() { try { throw new Error('myError'); } catch(e) { console.log(e.stack); } } function b() { trace(); } function a() { b(3, 4, '\n\n', undefined, {}); } a('first call, firstarg');
错误信息为:
Error: myError
at trace (
at b (
at a (
at
以上为抛错的构造函数的总结,如有误之处欢迎扶正。
The above is the detailed content of Introduction to JavaScript error handling mechanism (with examples). For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),