Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

Go’s type system catches many errors at compile time, but some errors can only be checked at run time, such as group access overbounds, null pointer references, and so on. These runtime errors cause painc exceptions.

When a Panic exception occurs, the program interrupts and immediately executes the functions that have been delayed in the Goroutine (the defer mechanism). The program then crashes and outputs log messages.

The log information includes panic value and function call stack trace information.

Panic value is usually some kind of error message. For each Goroutine, the log information contains the corresponding stack trace of the function call when panic occurred.

Usually, we do not need to run the program again to locate the problem, and the log information provides sufficient diagnostic evidence.

Cause Panic

Not all Panic exceptions come from the runtime. Direct calls to the built-in Panic function can also raise panic exceptions. The panic function accepts any value as an argument. We should call Panic when something happens that should not happen.

For example, when the program reaches some logically impossible path:

switch s := suit(drawCard()); 
s {
    case "Spades":                                // ...
    case "Hearts":                                // ...
    case "Diamonds":                              // ...
    case "Clubs":                                 // ...
    default:
        panic(fmt.Sprintf("invalid suit %q", s)) // Joker?
}
Copy the code

Applicable scenario

While Go’s Panic mechanism is similar to exceptions in other languages, panic applies to a few different scenarios.

Since panic can cause a program to crash, panic is commonly used for serious errors, such as inconsistencies in logic within a program.

Any crash indicates a bug in the code, so for most bugs, we should use the error mechanism provided by Go instead of Panic to try to avoid crashes. In a robust program, any expected errors such as incorrect input, incorrect configuration, or failed I/O operations should be handled gracefully, best handled by using Go’s error mechanism.

Recover Catch exception

We can recover from an exception, or at least we can do something about it before it crashes.

For example, when a Web server encounters unexpected and severe problems, all connections should be closed before crashing; If no action is taken, the client will remain in a waiting state. If the Web server is still under development, the server can even feed exception information back to the client to help with debugging.

If the built-in function Recover is called in the deferred function and a Panic exception occurs in the function that defines the defer statement, Recover causes the program to recover from Panic and return Panic value. The function that caused panic does not continue, but returns normally. If recover is called without panic, recover returns nil.

The Deferred function helps Parse recover from Panic. Inside the deferred function, panic value is appended to the error message; The error message is received with the err variable and returned to the caller. We can also add the complete Stack call information to the error message by calling Runtime. Stack.

func Parse(input string) (s *Syntax, err error) { defer func() { if p := recover(); p ! = nil { err = fmt.Errorf("internal error: %v", p) } }() // ... parser... }Copy the code

– END –

Author: The road to architecture Improvement, ten years of research and development road, Dachang architect, CSDN blog expert, focus on architecture technology precipitation learning and sharing, career and cognitive upgrade, adhere to share practical articles, looking forward to growing with you. Attention and private message I reply “01”, send you a programmer growth advanced gift package, welcome to hook up.

Thanks for reading!