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

How JavaScript customizes exceptions

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article is about how JavaScript customizes exceptions. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. Concept

1.1 what are errors and exceptions

The so-called error is the state in which the program does not work properly in the process of programming, also known as an exception.

All exceptions in JavaScript are Error objects, and when an exception is encountered, an Error object is thrown, which contains incorrect description information.

Through the exception handling statements provided by JavaScript, we can catch errors in a structured way and separate the exception handling code from the core business code.

1.2 Classification of exceptions

In actual development, exceptions can be divided into the following three main types:

Logic errors: logic errors are the most difficult types of errors to track. These errors are due to logical errors in the running of the program, so that your script does not get the results you want.

JavaScript comes with errors: these are the most common types of errors, such as JavaScript syntax errors, code reference errors, type errors, and so on, which are automatically triggered by JavaScript's engine.

Errors thrown by developers: they are usually defined by developers to meet their needs.

two。 Exception handling

2.1try...catch statement

The try...catch statement is a standard way to handle exceptions in JavaScript, and the syntax structure is as follows:

Try {/ / Code blocks for testing} catch (err) {/ / Code blocks handling errors}

Parameters:

Try: statements allow you to define a block of code to detect errors at execution time.

Catch: statement allows you to define a block of code to be executed, which will be executed if an error occurs in the block of try code

Err: an identifier that represents an Error object with the type of error corresponding to the error in the test block.

The sample code is as follows:

Try {/ / used to test the block of code console.log (v) / / when v is not defined, an exception will be thrown} catch (error) {/ / throwing an exception will execute this block of code console.log ('error in the above code')}

It is worth noting that * * try and catch** statements appear in pairs

2.2finally statement

The finally statement, also known as the terminating block, is executed after the end of the try and catch statements, regardless of whether the result is incorrect or not.

The syntax structure is as follows:

Try {/ / Code blocks for testing} catch (err) {/ / Code blocks handling errors} finally {/ / Code blocks executed regardless of the try catch result}

The sample code is as follows:

/ / var vtry {/ / used to test the block of code console.log (v) / / when v is not defined, an exception will be thrown} catch (error) {/ / throwing an exception will execute this block of code console.log ('error in the above code')} finally {console.log ('I must be executed')} 2.3throw statement

The throw**** statement is used to throw a user-defined exception. This exception can be any data type. When the throw statement is executed, the current execution will be stopped, and if there is a catch block, the catch block will be executed, otherwise it will jump out of the loop.

The syntax format is as follows:

Throw expression

Expression: the expression to be thrown

Use the throw statement to throw an exception. When you throw an exception, expression specifies the contents of the exception.

The sample code is as follows:

/ / throw "error" / / output error throw false / / output false

Of course, throw can also be followed by an object.

3.Error object

An error object can be created through the constructor of Error. When a runtime error occurs, an instance object of Error is thrown. In general, errors of Error type are rare, basically they are of other error types, but other error types are inherited from Error.

The Error object is primarily used as the base object for user-defined exceptions.

In addition to the Error object, JavaScript provides the following predefined types of errors

The error name describes the error that EvalError has occurred in the eval () function RangeError has occurred an error outside the numeric range ReferenceError has occurred illegal reference SyntaxError has occurred syntax error TypeError has occurred type error URIError has occurred error in encodeURI ()

There are two main attributes of Error:

Property describes the name setting or returns the error name message setting or returns an error message (a string)

The instance syntax format for creating an Error object is as follows:

New Error ([message)

Parameters:

Message: optional, described error message

Other predefined types have the same creation syntax as Error

3.1 Custom exception types

If the exception type provided by JavaScript does not satisfy us, we can customize our own exception type. This custom exception type generally inherits the exception type of Error, and can be expressed as belonging to that exception type by the instanceof keyword.

Let's first take a look at the properties and methods provided in Node.js for customizing exception types

As follows:

Error.stack: attribute: returns a string whose first line is formatted as: with a series of stack frames (each line begins with "at"). Each frame describes a call point in the code that causes the error to be generated.

The Error.captureStackTrace (targetObject [, constructorOpt]) method: targetObject represents an object, and constructorOpt represents the object's constructor. What it does: create a .stack property on targetObject

The sample code is as follows:

Function MyError (message) {this.message = message this.name = 'MyError' / * * Error.captureStackTrace (targetObject [, constructorOpt]) * parameter targetObject-> indicates an object * parameter constructorOpt-> indicates the object's constructor * creates a .stack property on targetObject, and the call returns a string that calls the location of Error.captureStackTrace (). * / Error.captureStackTrace (this, MyError)} MyError.prototype = new Error () MyError.prototype.constructor = MyError// * in node.js environment, new Error will directly throw an exception not suitable for node.js environment / / function MyError (message) {/ / this.name = 'MyError';// this.message = message | |' Default Message';// this.stack = (new Error ()). Stack;//} / / MyError.prototype = Object.create (Error.prototype) / / MyError.prototype.constructor = MyError;try {throw new MyError (wrong)} catch (e) {console.log (e)} Thank you for reading! This is the end of this article on "how to customize exceptions in JavaScript". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

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