swift exception handling in the History
- Swift1.0 Cocoa Touch version of NSError, Swift does not really have its own exception handling mechanism
- Swift2.0 version added ErrorType protocol
- Swift3.0 version renamed Error protocol
Use of Swift3.0 Error protocol
First, the definition of an enumerated, integration protocol Error (Swift 2.0 protocol is called ErrorType, 3.0 renamed Protocol Error)
|
|
Use throws and throw the
Throws back the parameter list used in a method of indicating an exception is thrown, the standard format: func 方法名字 (参数列表) throws -> 返回值类型
using throw thrown in the method
|
|
Using the do-catch handle exceptions
|
|
try?的使用
Swift2.0 后加入了新的关键字 try?
, 如果不想处理异常那么可以用这个关键字,使用这个关键字返回一个可选值类型,如果有异常出现,返回nil.如果没有异常,则返回可选值.例子如下
|
|
控制台输出
`nil
Program ended with exit code: 0`
try!的使用
如果不想处理异常,而且不想让异常继续传播下去,可以使用try!.这有点儿类似NSAssert().但是一旦使用try!后,在可能抛出异常的方法中抛出了异常,那么程序会立刻停止.例子如下
|
|
控制台:程序奔溃掉~
try try? try! 的区别
- try 出现异常处理异常
- try? not handle the exception, an optional return value type, abnormal returns nil
- try! prevent abnormal continue to spread, once the program appears to stop abnormal, similar NSAssert ()