GO語言異常處理機制panic和recover分析_Golang

來源:互聯網
上載者:User

本文執行個體分析了GO語言異常處理機制panic和recover。分享給大家供大家參考。具體如下:

Golang 有2個內建的函數 panic() 和 recover(),用以報告和捕獲運行時發生的程式錯誤,與 error 不同,panic-recover 一般用在函數內部。一定要注意不要濫用 panic-recover,可能會導致效能問題,我一般只在未知輸入和不可靠請求時使用。

golang 的錯誤處理流程:當一個函數在執行過程中出現了異常或遇到 panic(),正常語句就會立即終止,然後執行 defer 語句,再報告異常資訊,最後退出 goroutine。如果在 defer 中使用了 recover() 函數,則會捕獲錯誤資訊,使該錯誤資訊終止報告。

樣本:

複製代碼 代碼如下:
package main

import (
 "log"
 "strconv"
)

//捕獲因未知輸入導致的程式異常
func catch(nums ...int) int {
 defer func() {
  if r := recover(); r != nil {
   log.Println("[E]", r)
  }
 }()

 return nums[1] * nums[2] * nums[3] //index out of range
}

//主動拋出 panic,不推薦使用,可能會導致效能問題
func toFloat64(num string) (float64, error) {
 defer func() {
  if r := recover(); r != nil {
   log.Println("[W]", r)
  }
 }()

 if num == "" {
  panic("param is null") //主動拋出 panic
 }

 return strconv.ParseFloat(num, 10)
}

func main() {
 catch(2, 8)
 toFloat64("")
}


輸出如下:

2014/11/01 22:54:23 [E] runtime error: index out of range
2014/11/01 22:54:23 [W] param is null

希望本文所述對大家的GO語言程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.