This is a created article in which the information may have evolved or changed.
Usage of exception handling painc () and recover () in the Go language
1. Painc usage is: used to throw an error. The Recover () usage is: Write Recover () in defer, and call this defer before the place where panic can occur (let the code execute when the System Method field ends.) When the program encounters a panic (of course, it can also call the normal exception), the system will skip the following code, enter defer, if the defer function recover (), then return the captured panic value.
2. Code:
Package Mainimport "FMT" Func Main () {FMT. Printf ("Hello World My Name is%s, I ' m%d\r\n", "Songxingzhu", "page") defer func () {if err: = Recover (); Err! = nil {fmt. Println ("Wrong:", Err)}} () Mypainc () fmt. Printf ("This should not be done here!") ")}func Mypainc () {var x = 30var y = 0//panic (" I am a big mistake! ") ") var C = x/yfmt. Println (c)}
3. Execution Result:
Atom Runner:main.gohello World My name is Songxingzhu, I ' m 26 out of the wrong: runtime Error:integer divide by zeroexited with code=0 In 1.667 seconds