swift 4.2 官方文档学习笔记(十二)- Error Handling

Sellen Wei
2 min readDec 18, 2018

--

There are four ways to handle errors in Swift. You can propagate the error from a function to the code that calls that function, handle the error using a do-catchstatement, handle the error as an optional value, or assert that the error will not occur.

  1. Swift 中的错误处理并不涉及解除调用栈,这是一个计算代价高昂的过程。???

2. build up error handling system and use do-catch to catch the errors:

3. 可以使用 try? 通过将错误转换成一个可选值来处理错误。例如,在下面的代码中,xy 有着相同的数值和等价的含义:

4. try!Disabling Error Propagation 禁用错误传递。 某个 throwing 函数实际上在运行时是不会抛出错误的,如果真的抛出了错误,你会得到一个runtime error。

let photo = try! loadImage(atPath: "./Resources/John Appleseed.jpg")

5. Specifying Cleanup Actions: defer的使用,当block结束时被强制执行,不管block是如何结束的,第一条 defer 语句中的代码最后才执行,第二条 defer 语句中的代码倒数第二个执行,以此类推。

--

--