An analysis of exception handling in LUA programming

Source: Internet
Author: User
Tags arithmetic assert error handling exception handling lua

This article mainly introduces the exception handling in LUA programming, which is the basic knowledge in Lua's introductory study, and the friend who wants to refer to

Error handling is required

Error handling is necessary because operations in the real world typically require complex operations, including file operations, database transactions, and Web service invocations. No one cares about the wrong business, it's a big loss when it comes to confidential information or money trading.

In any programming, there is always the need for error handling. Errors can be of two types, including the

Syntax error

Run-time error

Syntax error

Syntax errors occur in various program components, such as operators and expressions, caused by improper use. A simple example of a syntax error is shown below.

The code is as follows:

A = = 2

As you know, there is a difference between using single equals and double equals. Using an alternate alternative can cause an error. Equal to means allocation, comparison. In the same way, it represents and has a function that it is intended to implement.

Another example is a syntax error as shown below.

The code is as follows:

For A= 1,10

Print (a)

End

When we run the above program, we get the output below.

The code is as follows:

Lua:test2.lua:2: ' Do ' expected near ' print '

A syntax error is easier to handle than a run-time error because Lua interprets a run-time error with a more clearly positioned error ratio. From the above error, we can easily know that adding a do statement before the print statement is required for each LUA structure.

Run-time error

If a run-time error occurs, the program executes successfully, but it may result in improper input or handling, and the feature Run-time error is due to an error. A simple example to show the Run-time error is shown below.

The code is as follows:

function Add (a,b)

Return a+b

End

Add (10)

When we build the program, it will be successfully built and run. Once run, it runs and displays a run-time error.

The code is as follows:

Lua:test2.lua:2: Attempt to perform arithmetic on the local ' B ' (a nil value)

Stack Traceback:

Test2.lua:2: In function ' Add '

Test2.lua:5: in main chunk

[C]:?

A run-time error occurs because it is not a two variable. The expected value of the B parameter is nil and generates an error.

Maintenance and failure features

In order to handle errors, we often use two function assertions and errors. A simple example is shown below.

The code is as follows:

Local function Add (a,b)

ASSERT (Type (a) = = "Number", "A is not a number")

ASSERT (type (b) = = "Number", "B is not a number")

Return a+b

End

Add (10)

When we run the above program, we get the following error output.

The code is as follows:

Lua:test2.lua:3: B is not a number

Stack Traceback:

[C]: in function ' assert '

Test2.lua:3: In function ' Add '

Test2.lua:6: in main chunk

[C]:?

Error errors (messages [, level]) end the last called protection function and return the error message of the information. The error of this function will not return. In general, errors add some information about the wrong location at the beginning of a message. The level parameter specifies how to get the wrong location. Level 1 (default), where the error function is invoked. The 2-level error where the call to the wrong function is called, and so on. Pass a 0-level message that avoids adding an error to the location information.

Pcall and Xpcall

Programming in Lua to avoid raising these errors and handling errors requires the use of features Pcall or Xpcall.

Pcall (f, arg1, ...) function to invoke the functionality required by the protection mode. If there are some errors in function f, it does not raise an error. It simply returns the wrong state. A simple example of using Pcall is shown below.

The code is as follows:

function MyFunction ()

n = N/nil

End

If Pcall (myfunction) Then

Print ("Success")

Else

Print ("Failure")

End

When we run the above program, we get the output below.

The code is as follows:

Failure

The Xpcall (f, Err) function calls the required functionality and also sets an error handler. F any error does not propagate; Instead, Xpcall captures the error, demands the ERR function with the original Error object, and returns a status code.

A simple example for Xpcall is shown below.

The code is as follows:

function MyFunction ()

n = N/nil

End

function MyErrorHandler (ERR)

Print ("ERROR:", err)

End

Status = Xpcall (MyFunction, MyErrorHandler)

Print (status)

When we run the above program, we get the output below.

The code is as follows:

Error:test2.lua:2: Attempt to perform arithmetic on global ' n ' (a nil value)

False

As a programmer, the most important thing is to ensure correct error handling. Using error handling ensures that conditions that are beyond the bounds of the boundary conditions are not disturbed and are not interfered with by the user of the program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.