[swift学习之九]异常处理

来源:互联网 发布:nginx 子域名跨域配置 编辑:程序博客网 时间:2024/06/06 06:39
/*注意点: 1:没有最后的catch{}还不行,报错. 2:调用能够抛出异常的函数的时候,得加try关键字。并且如果出现异常了,后面的就不执行了,直接进catch,    这个和别的语言一样~。 3:函数后面得加throws关键字,否则不让抛出异常。 4:try!这个东西得慎用,表示调用的是带抛出异常的函数,但一定不抛出异常。如果判断错误,出现异常就悲剧了~ 5:标记throws的函数,抛出什么异常都无所谓,不一样类型都可以。 6:guard语法很特别,监测合法性,否则不往下执行。必须和else一起用。类似finally语法。 7:defer这个玩意在playground里面不执行,在正式工程里面没问题。 8:带附加数据的枚举异常,在catch的时候,得写附加值,比较能否catch到。 9:catch ...{}不要异常对象,catch let a as ...捕获后面的类型对象,就是看是否能类型转换成功~*/enum ErrorOverFlow:ErrorType{    case LowOverFlow(String,Int,Int)    case HighOverFlow(String,Int,Int)    case EmptyError(String)    func Description() -> String {        switch self {        case .LowOverFlow(let text, let minIndex, let CurrIndex):            return "\(text)Min:\(minIndex) currIndex:\(CurrIndex)"        case .HighOverFlow(let text, let maxIndex, let CurrIndex):            return "\(text)Max:\(maxIndex) currIndex:\(CurrIndex)"        case .EmptyError(let text):            return "\(text)"        }    }}enum ErrorIntValue:ErrorType{    case MaxValue(String,Int,Int)    case MinValue(String,Int,Int)    func Description() -> String {        switch self {        case .MinValue(let text, let minIndex, let CurrIndex):            return "\(text)Min:\(minIndex) currValue:\(CurrIndex)"        case .MaxValue(let text, let maxIndex, let CurrIndex):            return "\(text)Max:\(maxIndex) currValue:\(CurrIndex)"        }    }}class ErrorMustSix:NSError{    }func GetValueByIndex(aArray: [Int], aIndex:Int) throws->Int  {    guard !aArray.isEmpty else {       throw ErrorOverFlow.EmptyError("访问的数组内容为空")    }    guard aIndex < aArray.count else{        throw ErrorOverFlow.HighOverFlow("上标越界", aArray.count, aIndex)    }    guard aIndex >= 0 else{        throw ErrorOverFlow.LowOverFlow("下标越界", aArray.count, aIndex)    }    let rResult = aArray[aIndex]    guard rResult < 10 else{        throw ErrorIntValue.MaxValue("值太大", 10, rResult)    }    guard rResult > 1 else{        throw ErrorIntValue.MinValue("值太小", 1, rResult)    }    guard rResult > 5 else {        throw NSError(domain: "不能小于5啊!~", code: 5, userInfo: nil)    }    guard rResult < 7 else {        throw ErrorMustSix(domain: "不能大于7啊!~", code: 5, userInfo: nil)    }    return rResult}func CatchThrow() -> Void {    defer{        print("收尾了")    }    do{       let rResult = try GetValueByIndex([1,2,6],aIndex: 2)       print(rResult)    }    catch ErrorOverFlow.LowOverFlow("下标越界", 2, -1){        print("a")    }    catch let e as ErrorOverFlow  {        print(e.Description())    }    catch let e as ErrorIntValue{        print(e.Description())    }    catch let e as ErrorMustSix{        print(e)    }    catch let e as NSError{        print(e)    }    catch{            }}CatchThrow()
参考:http://www.swiftvip.cn/guide/chapter2/18_Error_Handling.html
0 0
原创粉丝点击