简体   繁体   中英

Swift 2: Catching errors in a closure

I've got the following code, which uses a closure to lazily initialize a property:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    do {
        try coordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil)
    } catch let err as NSError {
        XCTFail("error creating store: \(err)")
    }
    return coordinator

}()

The code as written produces the error:

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

The code is marked with 'try' and the error is handled. When I move the closure into a separate function and call it here, everything works as expected.

Is there something about closures and do/try/catch that I don't understand, or have I encountered (yet another!) bug in the wonderful Swift 2 compiler?

The problem is that your catch does not catch all the possible exceptions, so the closure can still throw. Use a generic catch:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel:  self.managedObjectModel)
    do {
        try coordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil)
    } catch {
        XCTFail("error creating store: \(error)")
    }
    return coordinator
}()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM