• Swift4 异常处理Try_Catch的使用之初见


    前言

    从OC转Swift了。虽然Swift的官方语法的资料看了2遍了。还是在使用的时候遇到点问题。
    好记性,不如烂笔头。本篇不是高深的内容。只是作为初使用的记录。

    当想给一个函数使用try-catch。需要在函数后加个throws。具体使用,如下
    先有个错误的枚举

    enum ErrorType:Error{
        case ErrorTypeNil
        case ErrorType1
    }
    

    这里需要函数出错会抛出错误的情况,记住后面要加throws

    func largerThanEighteenthFunc(a:Int16?) throws {
        if let need = a ,need >= 18{
            print("need >>>> (need)")
            throw  ErrorType.ErrorTypeNil
        }else{
            print("need <=18")
            throw  ErrorType.ErrorType1
        }
    }
    

    不需要捕抓错误,可以使用try!或try?。但是不建议不建议使用try!,使用try?会更加安全。因为如果当有错误捕抓到时,程序会直接崩溃

    func notPrintError() {
            try? largerThanEighteenthFunc(a: nil)
        }
    
    
    

    如果只包含一个catch语句,那么所有的错误都会在这个catch中执行,能够捕抓其错误信息

     func oneCondition() {
            do {
                try largerThanEighteenthFunc(a: 9)
            } catch let error {
                print("error >>> (error)")
            }
        }
    

    在使用catch时,我们想它是能够进行模式匹配的、能够进行更精准的错误匹配处理。可以穷举多种情况。

    func twoCondition() {
        do {
            try largerThanEighteenthFunc(a: 20)
        } catch ErrorType.ErrorTypeNil {
            print(ErrorType.ErrorTypeNil)
        } catch ErrorType.ErrorType1 {
            print(ErrorType.ErrorType1)
        } catch { // 加入一个空的catch,用于关闭catch。否则会报错:Errors thrown from here are not handled because the enclosing catch is not exhaustive
        }
    }
    

    注意:在使用do-catch的时候。无论是不是把错误都穷举完,一定要写个空catch,不然会报错。
    这个错误就是

    Errors thrown from here are not handled because the enclosing catch is not exhaustive

    友情连接:

  • 相关阅读:
    “数学题”——传钱
    kafka笔记——入门介绍
    SpringBoot集成Dubbo+Zookeeper
    MySql基本语法
    动态规划
    总结
    Java反射
    软件清单
    Java IO操作
    Spring Boot AOP的使用
  • 原文地址:https://www.cnblogs.com/blogwithstudyofwyn/p/9855069.html
Copyright © 2020-2023  润新知