Exception handling and error handling

defer

Represents a delay calling, even serious procedural errors, will perform

main Package Penalty for 

Import  " fmt " 

FUNC main () { 
    the defer fmt.Println ( " I was the last to perform 1 " ) 
    the defer fmt.Println ( " I was the last to perform 2 " )   // performed first and then execute 2 1 
    f1 () 
    F2 ( ) 
} 

FUNC F1 () { 
    fmt.Println ( " F1 " ) 
} 
FUNC F2 () { 
    fmt.Println ( " F2 " ) 
}

 

panic、recover

panic is the python raise (the initiative to throw an exception), recover is to restore the program to continue execution

main Package 

Import  " FMT " 

FUNC main () { 
    F1 () 
    F2 () 
    F3 () 
} 

FUNC F1 () { 
    fmt.Println ( " F1 ... " ) 
} 

FUNC F2 () { 
    the defer FUNC () { 
        IF A : Recover = (); a =! nil {
             // a if not equal to nil, the program indicates an abnormality, a message is abnormal
             // a is equal to nil, indicating no abnormality 
            fmt.Println ( " wrong " ) 
        } 

    } ( ) 
    fmt.Println ( " F2 ... " ) 
    var A = the make ([] int, 3,3)
    fmt.Println(a[4])
}
func f3()  {

    fmt.Println("f3...")
}

Error Handling

Error indicates that the program appears in unusual circumstances. For example, when we try to open a file, the file system actually does not have this file. This is an abnormal situation, it is represented by an error.

In Go, the error has been very common. Wrong with the built-in  error types to represent.

Like other built-in types (such as  int, float64 etc.), error values can be stored in a variable, as the return value of the function and so on.

main Package 

Import (
     " errors " 
    " FMT " 
) 


FUNC circleArea (RADIUS int) (int, error) { 
    IF RADIUS < 0 {
         return 0, errors.New ( " error " ) // If the condition is determined will display an error information 
    } 
    return 100 , nil 
} 

FUNC main () { 
    A, _: = circleArea (-10 )
     IF ! ERR = nil { 
        fmt.Println (ERR) 
    } 
    fmt.Println (A) 
    _, ERR: = fmt.Println ( )
     IF ERR! ={nil 
        fmt.Println ( " Printing Error " ) 
    } 
}

 

 

Guess you like

Origin www.cnblogs.com/xiongying4/p/12030309.html