Swift4.2基础学习笔记(三)

2018-10-10  本文已影响0人  清灬影

参考资料与链接https://www.cnswift.org

错误处理

在程序执行阶段,你可以使用错误处理机制来为错误状况负责。

当一个函数遇到错误情况,他会抛出一个错误,这个函数的访问者会捕捉到这个错误,并作出合适的反应。

func canThrowAnError() throws{
    
}
//通过在函数声明过程当中加入 throws 关键字来表明这个函数会抛出一个错误。
//当你调用了一个可以抛出错误的函数时,需要在表达式前预置 try 关键字。
do {
    try canThrowAnError()
    // no error was thrown
} catch {
    // an error was thrown
}

断言和先决条件

使用断言进行调试

let age = -3
assert(age >= 0, "A person's age cannot be less than zero")

//如果代码已经检查了条件,你可以使用 assertionFailure(_:file:line:) 函数来标明断言失败
if age > 10 {
    print("You can ride the roller-coaster or the ferris wheel.")
} else if age > 0 {
    print("You can ride the ferris wheel.")
} else {
    assertionFailure("A person's age can't be less than zero.")
}

强制先决条件

precondition(age > 0 , "Index must be greater than zero.")
上一篇 下一篇

猜你喜欢

热点阅读