Hi, I’m Mingo.

In their learning Golang this time, I wrote a detailed study notes on my personal number WeChat public Go programming time, for the language, I was a beginner, so writing should fit in with the new to classmates, if you are just learning the language, don’t focus on prevention, study together, Grow together.

My Github:github.com/iswbm/GolangCodingTime my online blog: golang.iswbm.com


Programming languages generally have exception catching mechanisms. In Python, exceptions are thrown and caught using the raise and try-except statements.

In Golang, there are a number of common errors that can be warned in advance at compile time, such as syntax errors or type errors, but some errors can only occur after the program runs, such as array access out of bounds, null pointer references, etc. These runtime errors cause the program to exit.

Of course, we can also trigger the program downtime and exit. For example, after checking and judging that the current environment cannot meet the expected conditions of our program (for example, a service designated listening port is occupied by other programs), we can manually trigger panic to let the program exit and stop running.

1. The triggering panic

Triggering an outage manually is a very simple matter, just call the built-in function Panic, like this

package main

func main() {
    panic("crash")
}Copy the code

After running, an error is reported

$ go run main.go
go run main.go
panic: crash

goroutine 1 [running]:
main.main()
        E:/Go-Code/main.go:4 +0x40
exit status 2Copy the code

2. Capture panic

When an exception occurs, it is sometimes necessary to catch it, just like except in Python. How does this work in Golang?

This leads to another built-in function, recover, which allows applications to recover after an outage.

However, one condition for using Recover is that it must take effect in the defer function; it does not work in other scopes.

This is a simple example

Import "FMT" func set_data(x int) {defer func() {// recover() can print the panic information if err := recover(); err ! = nil {fmt.println (err)}}() Var arr[10]int arr[x] = 88} func main() {set_data(20); FMT.Println("everything is OK ")}Copy the code

After running, the output is as follows

$ go run main.go
runtime error: index out of range [20] with length 10
everything is okCopy the code

Normally, should not be into the panic downtime do any processing program, but sometimes, need we can recover from outage, we can at least before the program crashes, do some operation, for example, when a web server unpredictable serious problems, should be before the collapse of all the connection is closed, if you don’t do any processing, This can keep the client in a waiting state, and if the Web server is still under development, the server can even send exception information back to the client to help debugging.

3. Unable to cross coroutines

As you can see from the above example, even though Panic causes the entire program to exit, you still have to finish defer if there is a defer function before you exit.

However, this defer has no effect among multiple coroutines. Panic was triggered in the sub-coroutine, and only the defer function in the coroutine itself could be triggered, instead of calling the defer function in the main coroutine.

Let’s do an experiment to find out

Import (" FMT ""time") func main() {// This defer will not defer fmt.println ("in main") go func() {defer Println("in ") goroutine") panic("") }() time.Sleep(2 * time.Second) }Copy the code

The output is as follows

in goroutine
panic:

goroutine 6 [running]:
main.main.func1()
        E:/Go-Code/main.go:12 +0x7b
created by main.main
        E:/Go-Code/main.go:10 +0xbc
exit status 2Copy the code

4. To sum up

To throw and catch Golang exceptions, we rely on two built-in functions:

  • Panic: Throws an exception and crashes the program
  • Recover: Catch exceptions, recover programs, or do close work

After the revocer call, the panic thrown will end here and will not be thrown out, but recover cannot be used arbitrarily. It has mandatory requirements and must be used under defer.

A series of reading

01. Setup of development environment (Goland & VS Code)

02. Learn five ways to create variables

03. Data type: **Integer and floating point **

Data types: byte, RUNe, and String

05. Data types: Array and slice

06. Data types: dictionary and Boolean

07. Data type: pointer

08. Object-oriented Programming: Structures and Inheritance

09. An article to understand the function in Go

10. Go language flow control: if-else conditional statements

11. Go language flow control: switch-case selection statement

12. Go language flow control: for loop statement

13. Go language flow control: GOto unconditional jump

14. Go language flow control: defer the call

15. Object-oriented programming: Interfaces and polymorphism

Key words: make and new difference?

17. An article to understand the blocks and scopes in Go

18. Learn Go coroutine: Goroutine

19. Learn Go coroutines: Detail channels/channels

20. Several classic error cases of channel deadlock

21. Learn the Go coroutine: WaitGroup

22. Learn Go coroutines: mutex and read-write locks

23. Exception handling in Go: Panic and recover

24. Super detailed interpretation of Go Modules past life and the introduction to use

25. Go language about package import must learn 8 knowledge points

26. How to open source your modules for others to use?

27. What about type assertions in Go?

28. These five points will help you understand the select usage of Go