如何避免 "Terminating app due to uncaught exception"
How to avoid "Terminating app due to uncaught exception"
有时您会遇到异常并使应用程序崩溃。就我而言,这里:
+ (void)saveContext:(NSManagedObjectContext *)context
{
if ([context hasChanges]) {
[context performBlockAndWait:^{
NSError *error = nil;
BOOL saved = [context save:&error];
if (!saved) {
// do some real error handling
NSLog(@"Could not save master context due to %@", error);
}
else {
if ([context parentContext]) {
[self saveContext:[context parentContext]];
}
}
}];
}
}
由于迁移 Coredata 时保存上下文而终止。我不明白为什么那段代码没有逃脱异常。它不应该记录 "Could not save master context due to $error" 吗?
问题是,NSError 有什么意义吗?如何逃避异常和崩溃?我应该使用 @try-catch 而不是 NSError 吗?
编辑 1
所以,感谢下面的 TheEye 先生,我知道 NSError 不会逃避这个 uncaught exception
,为了避免崩溃,我最好改用 @try-catch。
但是,"it would be better to correct the cause of the exception, as it should not happen.",所以我认为最好将问题更新如下:
如何让上下文等到迁移完成并执行保存?在迁移失败的情况下,我将删除所有上下文和持久存储,因此保存过程(以防迁移失败)应该无效。 else(迁移成功),正常保存。
编辑 2
所以,为了 "correct the cause of the exception",我最终修复了这样的保存上下文:
if (context.hasChanges && context.persistentStoreCoordinator.persistentStores.count) {
...
}
我的问题到此结束。感谢您花时间在这里。
错误对象仅用于预期错误 - 如果发生不可预见的事情(例如某些线程问题),将抛出异常。您可以使用 try/catch 捕获它,但最好纠正异常的原因,因为它不应该发生。
有时您会遇到异常并使应用程序崩溃。就我而言,这里:
+ (void)saveContext:(NSManagedObjectContext *)context
{
if ([context hasChanges]) {
[context performBlockAndWait:^{
NSError *error = nil;
BOOL saved = [context save:&error];
if (!saved) {
// do some real error handling
NSLog(@"Could not save master context due to %@", error);
}
else {
if ([context parentContext]) {
[self saveContext:[context parentContext]];
}
}
}];
}
}
由于迁移 Coredata 时保存上下文而终止。我不明白为什么那段代码没有逃脱异常。它不应该记录 "Could not save master context due to $error" 吗?
问题是,NSError 有什么意义吗?如何逃避异常和崩溃?我应该使用 @try-catch 而不是 NSError 吗?
编辑 1
所以,感谢下面的 TheEye 先生,我知道 NSError 不会逃避这个 uncaught exception
,为了避免崩溃,我最好改用 @try-catch。
但是,"it would be better to correct the cause of the exception, as it should not happen.",所以我认为最好将问题更新如下:
如何让上下文等到迁移完成并执行保存?在迁移失败的情况下,我将删除所有上下文和持久存储,因此保存过程(以防迁移失败)应该无效。 else(迁移成功),正常保存。
编辑 2
所以,为了 "correct the cause of the exception",我最终修复了这样的保存上下文:
if (context.hasChanges && context.persistentStoreCoordinator.persistentStores.count) {
...
}
我的问题到此结束。感谢您花时间在这里。
错误对象仅用于预期错误 - 如果发生不可预见的事情(例如某些线程问题),将抛出异常。您可以使用 try/catch 捕获它,但最好纠正异常的原因,因为它不应该发生。