- 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.
推薦閱讀
- 計算機信息技術(shù)基礎(chǔ)實驗與習(xí)題
- Access 2016數(shù)據(jù)庫技術(shù)及應(yīng)用
- Mastering Machine Learning with R(Second Edition)
- Ceph源碼分析
- 數(shù)據(jù)庫技術(shù)實用教程
- SQL優(yōu)化最佳實踐:構(gòu)建高效率Oracle數(shù)據(jù)庫的方法與技巧
- 數(shù)據(jù)庫原理與應(yīng)用
- 聯(lián)動Oracle:設(shè)計思想、架構(gòu)實現(xiàn)與AWR報告
- 貫通SQL Server 2008數(shù)據(jù)庫系統(tǒng)開發(fā)
- 智能與數(shù)據(jù)重構(gòu)世界
- 云原生架構(gòu):從技術(shù)演進到最佳實踐
- Arquillian Testing Guide
- 數(shù)據(jù)庫基礎(chǔ)與應(yīng)用
- 實用預(yù)測分析
- Configuration Management with Chef-Solo