GO basis of exception handling

First, abnormal

1, the error refers to the abnormal situation occurs in a program, causing the program can not be executed properly.
• Most languages use try ... catch ... finally statement is executed.
Suppose we are trying to open a file, the file does not exist in the file system. This is an abnormal situation, it is expressed as a mistake.
2, Go language does not try ... catch

  • • Go language provides a very simple error handling mechanism via the built-in error types.
  • • error values ​​can be stored in a variable, returned by the function.
  • If a function or method returns an error, by convention, it must be the last value returned by the function.
  • • usual way to handle errors is to return error and nil for comparison.
  • nil value indicates that no error has occurred, rather than nil if an error occurred.
  • • If it is not nil, need to print out an error.

go in error source

package errors

// New returns an error that formats as the given text.
// Each call to New returns a distinct error value even if the text is identical.
func New(text string) error {
    return &errorString{text}
}

// errorString is a trivial implementation of error.
type errorString struct {
    s string
}

func (e *errorString) Error() string {
    return e.s
}

 

Two, go exception handling

 

 

 

package main

import (
    "math"
    "fmt"
    "os"
    "github.com/pkg/errors"
)

func main() {
    //     exceptions. 1 
    RES: Math.sqrt = (- 100 )
    fmt.Println(res)

    res , err := Sqrt(-100)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(res)
    }


    // anomalies 2
     // RES = 100/0
     // fmt.Println (RES) 
    RES, Divide ERR = ( 100 , 0 )
     IF ERR! = Nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println(res)
    }

    // exceptions. 3 
    F, ERR: = os.Open ( " /abc.txt " )
     IF ERR =! Nil {
        fmt.Println(err)
    } else {
        fmt.Println (F.Name (), " the file is opened successfully! " )
    }

}

// definition of the square root operation function 
FUNC Sqrt (float64 F) (float64, error) {
     IF F < 0 {
         return  0 , errors.New ( " negative square root can not be acquired " )
    } else {
        return math.Sqrt(f) , nil
    }
}

// definition of division function 
FUNC Divide (dividee float64, float64 Divider) (float64, error) {
     IF Divider == 0 {
         return  0 , errors.New ( " Error:! Divisor is not 0 " )
    } else {
        return dividee / divider , nil
    }
}
View Code

go to create a way in error

// error-create a 
FUNC Sqrt (float64 F) (float64, error) {
     IF F < 0 {
         return  0 , errors.New ( " negative square root can not be acquired " )
    } else {
        return math.Sqrt(f) , nil
    }
}
// error created Second way; a design function: to verify age. If it is negative, error is returned 
FUNC of CheckAge (Age int ) ( String , error) {
     IF Age < 0 {
        ERR: = fmt.Errorf ( " your age is entered:!% d, the value is negative, there is an error " , Age)
         return  "" , ERR
    } The else {
         return fmt.Sprintf ( " your age input is:% d " , Age), nil
    }
}

Fourth, custom error

• 1, definition of a structure, the type of error indicates that the custom
• 2, so that the type of custom method to achieve error interface errors: Error () String
•. 3, a function defined error return. According to the actual functionality of the program depends.

package main

import (
    "time"
    "fmt"
)

// 1, definition of the structure, the type of error indicates that the custom 
type MyError with the struct {
    When time.Time
    What string
}

//2、实现Error()方法
func (e MyError) Error() string {
    return fmt.Sprintf("%v : %v", e.When, e.What)
}

@ 3, defined function that returns the error object. The rectangular area seeking function 
func getArea (width, length float64) (float64, error) {
    errorInfo := ""
    if width < 0 && length < 0 {
        the errorInfo = fmt.Sprintf ( " length:% v, width:% v, are negative " , length, width)
    } else if length < 0 {
        the errorInfo = fmt.Sprintf ( " length:% v, negative numbers " , length)
    } else if width < 0 {
        the errorInfo = fmt.Sprintf ( " Width:% v, negative numbers " , width)
    }
    if errorInfo != "" {
        return 0, MyError{time.Now(), errorInfo}
    } else {
        return width * length, nil
    }
}

func main() {
    res , err := getArea(-4, -5)
    if err != nil {
        fmt.Printf(err.Error())
    } else {
        fmt.Println ( " area: " , RES)
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/jalja/p/11817447.html