- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 186字
- 2021-07-02 23:54:30
Error handling
Swift provides support to throw, catch, propagate, and manipulate recoverable errors at runtime.
Value types should conform to the Error protocol to be represented as errors. The following example presents some 4xx and 5xx HTTP errors as enum:
enum HttpError: Error {
case badRequest
case unauthorized
case forbidden
case requestTimeOut
case unsupportedMediaType
case internalServerError
case notImplemented
case badGateway
case serviceUnavailable
}
We will be able to throw errors using the throw keyword and mark functions that can throw errors with the throws keyword.
We can use a do-catch statement to handle errors by running a block of code. The following example presents JSON parsing error handling in a do-catch statement:
protocol HttpProtocol{
func didRecieveResults(results: Any)
}
struct WebServiceManager {
var delegate:HttpProtocol?
let data: Data
func test() {
do {
let jsonResult = try JSONSerialization.jsonObject(with:
self.data, options: JSONSerialization.ReadingOptions
.mutableContainers)
self.delegate?.didRecieveResults(results: jsonResult)
} catch let error {
print("json error" + error.localizedDescription)
}
}
}
We can use a defer statement to execute a set of statements just before code execution leaves the current code block, regardless of how the execution leaves the current block of code.
推薦閱讀
- 復雜性思考:復雜性科學和計算模型(原書第2版)
- Test-Driven Development with Mockito
- 文本數據挖掘:基于R語言
- 新型數據庫系統:原理、架構與實踐
- MySQL基礎教程
- Access 2016數據庫技術及應用
- 數據革命:大數據價值實現方法、技術與案例
- 大話Oracle Grid:云時代的RAC
- 數據庫原理與應用(Oracle版)
- INSTANT Apple iBooks How-to
- IPython Interactive Computing and Visualization Cookbook(Second Edition)
- SQL Server深入詳解
- 貫通SQL Server 2008數據庫系統開發
- 數據修復技術與典型實例實戰詳解(第2版)
- The Natural Language Processing Workshop