This is a creation in Article, where 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 main import "FMT" func Main () { fmt. Printf ( "Hello World My Name is%s, I ' m%d\r\n" , "Songxingzhu" , + ) & Nbsp; defer func () { if err: = Recover (); Err! = Nil { fmt. Println ( "Out of the wrong:" , Err) } } () mypainc () fmt. Printf ( "should not be executed here!") )}func Mypainc () { var x = ( var y = 0 //panic ( "I was a big mistake!" ) var c = x/y fmt. Println (c)}
3. Implementation results
Atom Runner: main. go
hello world my name is songxingzhu, I'm 26
出了错: runtime error: integer divide by zero
Exited with code=0 in 1.667 seconds
|
|