Swift 2:调用可以抛出,但是没有标记为'try'并且没有处理错误 [英] Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

查看:448
本文介绍了Swift 2:调用可以抛出,但是没有标记为'try'并且没有处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我安装Xcode 7 beta并将我的swift代码转换为Swift 2后,我遇到了一些我无法弄清楚的代码问题。我知道Swift 2是新的,所以我搜索并弄清楚,因为没有任何关于它,我应该写一个问题。

After I installed Xcode 7 beta and convert my swift code to Swift 2, I got some issue with the code that I can't figure out. I know Swift 2 is new so I search and figure out since there is nothing about it, I should write a question.

这是错误:


调用可以抛出,但没有标记为'try'且错误不是
处理

Call can throw, but it is not marked with 'try' and the error is not handled

代码:

func deleteAccountDetail(){
        let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
        let request = NSFetchRequest()
        request.entity = entityDescription

        //The Line Below is where i expect the error
        let fetchedEntities = self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
        }

        do {
            try self.Context!.save()
        } catch _ {
        }

    }

快照:

推荐答案

你必须抓住错误就像你已经为 save()做的那样调用,因为你在这里处理多个错误,你可以在一个do-catch块中依次尝试多次调用,如下所示:

You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
            self.Context!.deleteObject(entity)
        }

        try self.Context!.save()
    } catch {
        print(error)
    }
}

或者@ bames53在下面的评论中指出,通常更好的做法是不捕捉它被抛出的错误。您可以将方法标记为 throws 然后尝试来调用该方法。例如:

Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws then try to call the method. For example:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
    }

    try self.Context!.save()
}

这篇关于Swift 2:调用可以抛出,但是没有标记为'try'并且没有处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆