21 | Panic functions, recover functions, and defer statements (above)

Source: Internet
Author: User

In my last two articles, I described in detail Error handling in the Go language, and gives you a summary of the error types, processing techniques, and design methods for the error values from two perspectives.

in this article, I want to show you Another way of handling error in the Go language. However, strictly speaking, it does not deal with errors, but exceptions, and is an unexpected program exception.

This program exception is called panic, and I translate it into run-time panic. One of the "panic" word is translated by panic, and the reason is preceded by the "runtime" three words, because this exception will only be thrown out when the program is running.

For example, a The Go program has a slice, its length is 5, that is, the value of the element in the slice index is 0, 1, 2, 3, 4, but I in the program want to access the element value through index 5, it is obvious that such access is not correct.

Go program, specifically the program's Embedded go Language runtime system, throws an "index out of range" panic when executing to this line of code, prompting you to index out of bounds.

of course, it's not just a hint. When panic is thrown, if we do not add any protection to the program, the program (or the process that represents it) will terminate the operation after printing out the details of the panic (hereinafter referred to as panic details).

now, let 's take a look at what's in this panic detail.

Panic:runtime Error:index out of range

Goroutine 1 [Running]:

Main.main ()

/users/haolin/geektime/golang_puzzlers/src/puzzlers/article19/q0/demo47.go:5 +0x3d

Exit Status 2

Copy Code

The first line of this detail is "Panic:runtime error:index out of range". The meaning of "runtime error" is that this is a panic thrown in a runtime code package . In this panic, a runtime is included. The value of the error interface type. Runtime. Error interface embedded in the error interface and do a little expansion, runtime package has many of its implementation types.

In fact, the "Panic:" right side of This detail is exactly what this panic contains. The string representation of the value of the error type.

In addition,Panic details typically contain code execution information about the goroutine that is associated with its cause. As described in the above details, "Goroutine 1 [Running]", which indicates that an ID of 1 Goroutine is running when this panic is raised.

Note that here's the ID doesn't really matter, because it's just a goroutine number given inside the Go language runtime system that we can't get and change in the program.

let's look at the next line,"Main.main ()" shows that the Goroutine wrapper go function is the command source file in the main function, that is goroutine here is the main goroutine. The following line indicates which line of code in this goroutine is being executed when this panic is raised.

This includes the number of lines in the source file to which this line code belongs, and the absolute path to the source file. The last +0x3d of this line represents the entry count offset of this line of code relative to the function it belongs to. In general, however, it is of little use.

Finally,"Exit Status 2" indicates that my program is running at the end of exit status Code 2. In most operating systems, as long as the exit status code is not 0, it means that the program is running abnormally close. In the Go language, the exit status code, which causes the program to end running because of panic, will generally be 2.

In summary, as we can see from the above panic details, the code that is the source of this panic is in the 5th line of the Demo47.go file, and is included in the main function of the main package (that is, the code package where the command source file resides).

Well, my first question came along. My question today is: What is the approximate process of being thrown from panic to the end of a program operation?

The typical answer to this question is this.

let's start with a general procedure: a line of code in a function intentionally or unintentionally throws a panic. At this point, the initial panic details are established, and the control of the program is immediately transferred from this line of code to the line of code that invokes the function it belongs to, that is, the previous level in the call stack.

This also means that the execution of the function to which this line code belongs is terminated. Immediately thereafter, control does not stop there for a moment, and it shifts to the next level of call code. Control is propagated to the top of the stack in the opposite direction, which is the outermost function we write.

The outermost function here refers to the Go function, which is the main function for the primary goroutine . But control does not stay there, but is retracted by the Go language runtime system.

Subsequently, the program crashes and terminates, and the process that the hosting program runs on will die and disappear. At the same time, in the process of this control spread,The panic details are gradually accumulated and perfected, and will be printed out before the program terminates.

Problem Resolution

Panic may have been accidentally (or accidentally) triggered by an index that was out of bounds as described earlier. This kind of panic is real and unexpected in our program anomalies. But beyond that, we can deliberately trigger panic.

The Go language's built-in function panic is designed to trigger panic. The Panic function allows program developers to report exceptions while the program is running.

Note that this is completely different from the meaning of returning an error value from a function. When our function returns a non-nil error value, the caller of the function has the right to choose not to handle it, and the consequences of not handling are often not fatal.

The "Not Deadly" here means that the program is not able to provide any functionality (or zombie) or crash directly and terminate the operation (that is, true death).

However, when a panic occurs, if we do not impose any protections, the immediate consequence is that the program crashes, as described earlier, which is clearly fatal.

to show more clearly the process described in the answer, I wrote the demo48.go file. You can take a look at the code, try running it, and see what it means to print.

I'll remind you a little bit here. panic details will be gradually accumulated and perfected in the process of control transmission, and control will propagate to the top of the call stack in the opposite direction at the first level.

therefore, in the Code execution information for a goroutine, the information at the bottom of the call stack appears first, then the information that is called at the top level, and so on, and finally the information at the end of the call stack.

For example, the main function calls the Caller1 function, and the Caller1 function calls the Caller2 function, then the execution information of the code in the Caller2 function appears first, then the execution information of the code in the Caller1 function, and finally the information of the main function.

Goroutine 1 [Running]:

Main.caller2 ()

/users/haolin/geektime/golang_puzzlers/src/puzzlers/article19/q1/demo48.go:22 +0x91

Main.caller1 ()

/users/haolin/geektime/golang_puzzlers/src/puzzlers/article19/q1/demo48.go:15 +0x66

Main.main ()

/users/haolin/geektime/golang_puzzlers/src/puzzlers/article19/q1/demo48.go:9 +0x66

Exit Status 2

Copy Code

Well, here, I believe you have a certain understanding of the procedure termination process after panic was triggered. An in-depth understanding of this process and the proper interpretation of panic details should be our essential skills, which is important when debugging go programs or troubleshooting bugs for go.

Summary

In the last two articles, we are focusing on panic functions, recover functions, and defer statements. Today I mainly talk about the panic function. This function is specifically used to induce panic. Panic can also be called a run-time panic, which is a program exception that can only be thrown during a program run.

The run-time system of the Go language can automatically throw panic when a program has a critical error, and we can also raise panic by calling the panic function when needed. However, if you do not handle it, panic will cause the program to crash and terminate the operation.

Study Questions

how can a function convert panic to an error type value and return it to the caller as the result of the function?

21 | Panic functions, recover functions, and defer statements (above)

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.