go异常处理

1.panic("error message") 在任何地方都可以执行,后续代码不会在执行,类似php的die。panic用于抛出异常, recover用于捕获异常.
package main
import "os"
import "fmt"
func main() {
    var user = os.Getenv("USER")
    if user == "" {
        panic("The USER environment variable is not set.")
    }
   fmt.Println("continue exec")
}
 
运行结果:panic: The USER environment variable is not set.
 
2. recover
recover只能在defer语句中使用, 直接调用recover是无效的.recover()方法有一个返回值,如果recover()捕获到panic,则返回panic对象,否则返回nil。类似php的try{} catch() {}
 
package main
import "fmt"

func f1() {
    fmt.Println("This is f1()")
}

func f2() {
    defer func() {
        if err := recover(); err != nil {
            fmt.Println("Exception has been caught.")
        }
    }()
    fmt.Println("This is f2()")
    panic(1)
}

func f3() {
    fmt.Println("This is f3()")
}

func main() {
    f1()
    f2()
    f3()
}
 
运行结果
  This is f1()
  This is f2()
  Exception has been caught.
  This is f3()
 
通过在f2的defer函数中调用recover,捕获了异常,程序恢复正常的执行,继续执行f3
 
3.defer
defer语句延迟执行一个函数,该函数被推迟到当包含它的程序返回时(包含它的函数 执行了return语句/运行到函数结尾自动返回/对应的goroutine panic)执行。defer的函数的任何返回值都会被丢弃。 在声明时不会立即执行,而是在函数 return 后,再按照 FILO (先进后出)的原则依次执行每一个 defer.
 
package main
import "fmt"

func fn(n int) int {
 defer func() {
  n++
  fmt.Println("3st:", n)
 }()

 defer func() {
  n++
  fmt.Println("2st:", n)
 }()

 defer func() {
  n++
  fmt.Println("1st:", n)
 }()
 return n //没有做任何事情
}

func main() {
 fmt.Println("函数返回值:", fn(0))
}

  

运行结果:1st 1
     2st 2
     3st 3

原文地址:https://www.cnblogs.com/zhb-php/p/9389324.html