Go錯誤處理(二)

來源:互聯網
上載者:User

標籤:

1,.error介面的定義

 
  1. type error interface{
  2. Error() string
  3. }

2.error的使用
 
  1. func Foo(param int)(n int,err error){
  2. //函數定義
  3. }
  4. n,err:=Foo(0)
  5. if err!=nil{
  6. //錯誤處理
  7. }else{
  8. //使用傳回值n
  9. }
3.自訂error類型
  •     定義一個承載錯誤資訊的struct
 
  1. type PathError struct{
  2. op string
  3. path string
  4. Err error
  5. }
  •    定義Error方法

 
  1. func (e *PathError) Error() string{
  2.     return e.op+" "+e.path+":"+e.Err.Error()
  3. }

defer:相當於C#中的Filnaly,總會被執行,並且他的執行順序呢是先進後出
  
  1. func CopyFile(dst, src string) {
  2. defer fmt.Println(dst)
  3. defer fmt.Println(src)
  4. fmt.Println("copy")
  5. }

copy

c:\2.txt

c:\oem8.txt

panic:相當於throw,recover:相當於catch

 
  1. defer func() { //必須要先聲明defer,否則不能捕獲到panic異常
  2. if err := recover(); err != nil {
  3. fmt.Println(err) //這裡的err其實就是panic傳入的內容,55
  4. }
  5. }()
  6. f()
  7. func f() {
  8. fmt.Println("a")
  9. panic(55)
  10. fmt.Println("b")
  11. }
輸出為

a

55

這裡panic後面的fmt.Println("b")未被執行,所以後面的資訊沒有b

 

來自為知筆記(Wiz)

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.