Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the native error types of JavaScript

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces you to JavaScript's native error types. The content is very detailed. Interested friends can refer to it for reference. I hope it can help you.

From the browser console to the terminal running Node.js, we see errors everywhere.

Tip: Good false tips can make the difference between a fast and painless developmental experience and a slow and painful one. When writing reusable code, make sure you are writing error handling code that is clear and understandable.

1. RangeError

This error is thrown when the number is outside the allowed range of values.

for example

const l = console.logconst arr = [90,88] arr.length=90**99

We have an array with two elements of arr. Next, try expanding the array to contain 90**99 == 2.9512665430652753e+193 elements.

This number exceeds the range in which array sizes can grow. Running it throws RangeError:

$ node errors errors.js:4 arr.length=90**99 ^RangeError: Invalid array length

Because we want to increase the size of arr array beyond the range specified by JS.

2. ReferenceError

This error is raised when a reference to a variable or item is broken. The variable or item does not exist.

for example

const l=console.logconst cat = "cat" cat dog

There is a variable cat initialized to "cat". The cat variable and the dog variable are referenced next. The cat variable exists, but the dog variable does not.

cat will return "cat" and dog will raise a reference error because the name dog cannot be found in the environment record.

$ node errors errors.js:3 dog ^ReferenceError: dog is not defined

Every time we create or define a variable, the variable name is written to the environment record. Environment records are like key-value stores,

+-------------+ | Key | Value | --------------- | cat | "cat" | +-------------+

Every time we reference a variable, it stores variables defined in the program. When an environment value is found in a record and extracted and returned, the environment record is searched using the name of the variable as a key. Call an undefined function.

Now, when we create or define a variable without an assignment. Variable writes its key to the environment record as a variable name, but its value remains undefined.

var catenv record +-----------------+ | Key | Value | ------------------- | cat | undefined | +-----------------+

When a variable is assigned a value later, the variable is searched in the environment record and the assignment is overwritten when it is found to have no value defined.

var cat cat = "cat"env record +-------------+ | Key | Value | --------------- | cat | "cat" | +-------------+

So when the variable name is not found in the environment record, the JS engine raises a RefernceError.

+-------------+ | Key | Value | --------------- | cat | "cat" | +-------------+cat // "cat", yes, :) it's there dog // :( what's this? can't find it

Note: Undefined variables do not throw ReferenceError because the value in the environment record has not been set.

3. SyntaxError

This is the most common mistake. This error occurs when we enter code that the JS engine cannot understand.

JS engine caught this error during parsing. In JS engine, our code goes through different phases before we see the results on the terminal.

tokenization

parsing

explain

Tokenization breaks down the source of code into units. At this stage, numbers, keywords, words, and operators are classified and labeled separately.

The generated token stream is then passed to the parsing stage, where it is processed by the parser. This is where AST is generated from the tag stream. AST is an abstract representation of code structure.

In both the tokenization and parsing phases, if the syntax of our code does not conform to JS syntax rules, it will cause the phase to fail and raise SyntaxError. For example:

const l = console.loglet cat h = "cat"

What does the "h" in the code stand for? This "h" breaks the code.

$ node errors errors.js:3 let cat h = "cat" ^SyntaxError: Unexpected identifier

See, Node.js points out the problem. It says "h" is unexpected, which breaks the declaration of the cat variable.

Therefore, syntax errors can be said to occur during parsing or compilation.

4. TypeError

TypeError is used to indicate that an operation failed when there is no indication of the appropriate cause of failure in the other NativeError objects.

TypeError occurs when an operation is performed on the wrong data type, for example:

If we try to convert numbers to upper case, it looks like this:

const num = 123 num.toUpperCase()

This will cause TypeError.

$ node errors errors.js:4 num.toUpperCase() ^TypeError: num.toUpperCase is not a function

Because the toUpperCase function requires a string data type. The toUpperCase function is intentionally generic; it does not require its this value to be a String object. Therefore, it can be transferred to other kinds of objects for use as methods.

Only strings are converted to upper or lower case, and if we call the toUpperCase function on Objects, Boolean, Symbol, null, undefined data types, we get TypeError because it operates on the wrong data type.

5. URIError

This indicates the use of a global URI handler that is incompatible with its definition.

URI(Uniform Resource Indicator) in JS has the following functions: decodeURI, decodeURIComponent, etc.

If we call any of them with the wrong arguments, we will get a URIError.

decodeURI("%") ^URIError: URI malformed

encodeURI is used to get the unencoded version of the URI. ' %' is not the correct URI and therefore URIError was raised.

URIError is raised when there is a problem with URI encoding or decoding.

6. EvalError

When using the global eval() function, this is used to identify errors.

According to EcmaSpec 2018 Edition:

This exception is not currently used by this specification. It is retained for compatibility with previous versions of this specification.

7. InternalError

This error occurs inside the JS engine, especially when it has too much data to process and the stack grows beyond its critical limits.

This problem occurs when the JS engine is overwhelmed by excessive recursion and switching situations, etc.

switch(num) { case 1: ... break case 2: ... break case 3: ... break case 4: ... break case 5: ... break case 6: ... break case 7: ... break ... up to 1000 cases }

Here is a simple example of excessive recursion:

function foo() { foo() } foo()

As we say, everyone makes mistakes. As far as we knock code, it's a stable event. To overcome it, we need to know the types of native errors that can be thrown.

So whenever an error is raised in the terminal or browser, you can easily discover where and how it occurred and be able to write better, less error-prone code.

What are the native error types of JavaScript to share here, I hope the above content can be of some help to everyone, you can learn more knowledge. If you think the article is good, you can share it so that more people can see it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report