Chapter 21: Error Handling

大綱

What is error handling?

  • 一種處理失敗的藝術。

  • app中並不是所有事件都可以如我們程式碼預期一樣的結果,例如網路狀態,讀取文件的格式, 想想app什麼時會發生錯誤,並該如何處理。

Failable initializers

  • 透過Failable initializers回傳的是一個optional,而不絕對是一個instance, 用來處理init fail的error handle, 當init fail會回傳nil。

Optional chaining

  • 在層層複雜資料下,如何快速判斷某個property是否為optional, 不用一層一層的去解開,而是透過Optional chaining,只要當chaing的過程中,發現其中一個property為nil,就回傳nil。

Map and compactMap

  • Map的功能就是快速將array中的內容mapping到另外一個內容。

  • compactMap, 具有map的功能,另外還處理array萬一有nil的情況。

Error protocol

  • 任何type都可以實作error protocol, 但最好的type就是用enum。

Throwing errors

  • 定義好了error, 就是要用來處理程式中無法處理的case並throw對應的error。

Handling errors

  • Try: 根據不同的error進行對應的處理。

Not looking at the detailed error

  • Try?: 只想知道有error發生,不須特別知道是哪種error, 就可以使用,可以不用寫catch。

Stoping your program on an error

  • Try!: 當有error發生,強制中斷程式。

PugBot

Handling multiple errors

“Unfortunately, at this point, Swift’s do-try-catch system isn’t type-specific. There’s no way to tell the compiler that it should only expect PugBotErrors. To the compiler, that isn’t exhaustive, because it doesn’t handle each and every possible error that it knows about, so you still need a default case

Rethrows

  • 利用rethrow關鍵字,可以明確知道某個fun, 並沒有直接處理error, 而是將內部error在外拋出去。

Key points

  • A type can conform to the Error protocol to work with Swift’s error-handling system.

  • Any function that can throw an error, or call a function that can throw an error, has to be marked with throws or rethrows.

  • When calling an error-throwing function, you must embed the function call in a do block. Within that block, you try the function, and if it fails, you catch the error.

Last updated