Alternating throw

Does anyone know that there is syntax for try-catch of the next function of the region?

realm.write() {
  realm.add(whatever)
}

I get the following error:

the call may be executed, but it is not marked as "try", and the error is not processed

+4
source share
3 answers

From what I present, realm.write () can throw an exception. In Swift 2, you handle do / catch exceptions and try.

I suspect you should do something like this:

do {
   try realm.write() {
      realm.add(whatever)
   }
} catch {
    print("Something went wrong!")
}

If realm.write () throws an exception, the print statement will be called immediately.

+14
source

It seems that NSError is getting a throw. See Swift 2.0 Source

Add the answer to @tgebarowski:

do {
    try self.realm.write {
        realm.add(whatever)
    }
} catch let error as NSError {
    print("Something went wrong!")
    // use the error object such as error.localizedDescription
}
+5
source

try! realm.write {
    realm.add(whatever)
}
+1

Source: https://habr.com/ru/post/1608004/


All Articles