try… Catch is a useful feature in software development. Unfortunately, Go does not provide such syntax support directly, but Go does provide another syntax support, which is recover… Panic.
Although recover… Panic and try… The catch function is similar, but the programming philosophy is different:
try… Catch’s programming ideas
- Prevents code from exiting unexpectedly or crashing
try{ // Place file operations in try to prevent code exceptions open("file") } catch(ex){ log.print(ex) } finaly{ //.... } Copy the code
- Quickly return error information to prevent return from meaningless values
In other high-level languages, if you want to return two types of arguments, you usually need to define an aggregate structure type (e.g. struc or class).
try{ addUser({"name":"",age:0}) } catch(ex){ log.print(ex) } finaly{ //.... } class Result{string err int userId} func addUser(user) Result{if user.name==""{return Result{err:" user name is empty ", userId:0 } } var userId=save_to_db(user) return Result{ err:"", userId:123 } }Copy the code
recover… The programming ideas of Panic
This is a programming idea unique to Go, which states that all functions should return at least one error because go supports multiple returns. Although there are more and more languages with multiple return values in 2021, when Go language was born, almost no high-level languages supported multiple return values, and Go’s syntax at that time was quite simplified and advanced.
Programming philosophy: Code specification trumps everything else
All functions should contain at least one return value
func method(a) error{
ifError:return error("Something went wrong.")
return nil
}
Copy the code
Do not use panic to return error messages
Panic is used to terminate code that does not conform to expectations and continue execution. Catch makes no difference.
Panic should generally be used to end code snippets that cannot fix data problems on their own, and should be avoided if the problem is not fatal.
func init(a) {
if user == "" {
// This code is taken from the official tutorial. The examples are just examples. The following code should be avoided in accordance with the idea of creating panic by Go
panic("no value for $USER")
// Correct use should return an error
//return error("no value for $USER")}}Copy the code
recover… Panic is just a complement to Error
When we started with error in Go, our function would look something like this, and it would look long and ugly
iferr:=a(); err! =nil{}iferr=b(); Err! =nil{}iferr=c(); err! =nil{}Copy the code
When we had panic, our function could be written like this:
func test(a){
defer func(a){
if err:=recover(a); err! =nil{
log.print(err)
}
}()
a()
b()
c()
}
Copy the code
I understand it
try… The catch and recover… Panic is undoubtedly very similar, so similar that it can be understood as two ways of writing the same thing, but the inventor gave them different design ideas.