Swift 中 throws 异常抛出

一.异常抛出关键 throws 定义在函数结尾 如果函数有返回值 定义在 返回类型前如 :

func throwDeliver(num:Int) throws ->String


二.定义方法

//错误传递
    @discardableResult
    func throwDeliver(num:Int) throws ->String {
        print("错误传递")
        try numberTest(num: num)
        print("未传递错误")
        return "无错误"
    }
    func numberTest(num:Int) throws{
        if num == 1 {
            print("成功")
        }else if num == 2 {
            throw OperationError.ErrorTwo
        }else if num == 3{
            throw OperationError.ErrorThree("失败")
        }else {
            throw OperationError.ErrorOther
        }

    }


三、使用

1. 禁止异常传递,只有当你确定这个语句不会抛出异常你才可以这么做否则会引发运行时错误

print(try? throwDeliver(num: 1)+":禁止错误传递")

扫描二维码关注公众号,回复: 9099032 查看本文章
错误传递
成功
未传递错误
Optional("无错误:禁止错误传递")

print(try? throwDeliver(num: 5)+":禁止错误传递")

错误传递
nil

在执行到

print("错误传递")

try numberTest(num: num) 抛出异常 后续代码不在走下去

2.将异常转换成可选值,如果一个语句会抛出异常那么它将返回nil无论这个语句本来的返回值是什么:

 if let retureMessage = try? throwDeliver(num: 1) {
            print("可选值非空:"+retureMessage)

        }

错误传递
成功
未传递错误
可选值非空:无错误 

if let retureMessage = try? throwDeliver(num: 5) {
            print("可选值非空:"+retureMessage)

        }

错误传递 


3.使用do-catch捕获处理异常,在do闭包里面执行会抛出异常的代码,在catch 分支里面匹配异常处理异常

  do {
            print("do-catch 错误捕获")
            try throwDeliver(num: 1)
            print("未捕获错误")
        } catch  OperationError.ErrorOne {
            print("ErrorOne:")
        } catch OperationError.ErrorTwo {
            print("ErrorTwo:")
        } catch OperationError.ErrorThree(let discription) {
            print("ErrorThree:"+discription)
        }catch let discription{
            print(discription)
        }

do-catch 错误捕获
错误传递
成功
未传递错误
未捕获错误

do {
            print("do-catch 错误捕获")
            try throwDeliver(num: 5)
            print("未捕获错误")
        } catch  OperationError.ErrorOne {
            print("ErrorOne:")
        } catch OperationError.ErrorTwo {
            print("ErrorTwo:")
        } catch OperationError.ErrorThree(let discription) {
            print("ErrorThree:"+discription)
        }catch let discription{
            print(discription)

        }

do-catch 错误捕获
错误传递
ErrorOther


也可以在 catch 后不加 条件选择 直接输出 系统抛出的错误信息

        do {
            try throwDeliver(num: 3)
            print("未捕获错误")
        } catch
        {
            print(error)

        }

错误传递
ErrorOther


发布了255 篇原创文章 · 获赞 39 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/kangguang/article/details/80423491