美文网首页
try、try?、try!的使用方法

try、try?、try!的使用方法

作者: EngineerPan | 来源:发表于2021-09-13 16:19 被阅读0次
    enum NormalError: Error {
        case one
        case two
        case three
        case four
    }
    
    func say(words: String) throws -> String {
        switch words {
        case "one":
            throw NormalError.one
        case "two":
            throw NormalError.one
        case "three":
            throw NormalError.one
        case "four":
            throw NormalError.one
        default:
            return "ok"
        }
    }
    
    • try 的用法
      必须有捕获异常后的 catch 处理语句
    do {
        let result = try say(words: "five")
    } catch {
        print("出问题啦。。。。。")
    }
    
    • try?的用法
      不需要捕获异常后的 catch 处理语句
    // 返回值是一个可选类型,如果执行正常的话就存在返回值,否则如果抛出错误的话返回值为nil
    let result = try? say(words: "four")
    // 可选绑定
    if let res = try? say(words: "four") {
    }
    // 提前退出
    guard let resu = try? say(words: "four") else { return }
    
    • try!的用法
      不需要捕获异常后的 catch 处理语句
    // 对返回值进行强制解包,如果抛出错误则程序终止
    let res = try! say(words: "five")
    

    相关文章

      网友评论

          本文标题:try、try?、try!的使用方法

          本文链接:https://www.haomeiwen.com/subject/wzdfgltx.html