我有一个方法,它有几个部分可能引发异常。如果这些部件之一发生故障,我希望运行清洁方法。我正在考虑使用try / catch指令。
我的问题是:我是否必须对可能引发异常的每一行代码使用一个指令,还是可以将整个方法简单地包含在这样的块中?
@try {
[self doStuff];
// doStuff has several passages that could throw an exception
}
@catch (NSException * e) {
[self cleanTheWholeThing];
}
在这种情况下,对我来说不重要的是哪一行产生了问题。我只需要方法成功运行或在失败时做其他事情即可。
谢谢
最佳答案
您当然可以在try块中包含多行。例:
@try {
if (managedObjectContext == nil) {
actionMessage = @"accessing user recipe library";
[self initCoreDataStack];
}
actionMessage = @"finding recipes";
recipes = [self recipesMatchingSearchParameters];
actionMessage = @"generating recipe summaries";
summaries = [self summariesFromRecipes:recipes];
}
@catch (NSException *exception) {
NSMutableDictionary *errorDict = [NSMutableDictionary dictionary];
[errorDict setObject:[NSString stringWithFormat:@"Error %@: %@", actionMessage, [exception reason]] forKey:OSAScriptErrorMessage];
[errorDict setObject:[NSNumber numberWithInt:errOSAGeneralError] forKey:OSAScriptErrorNumber];
*errorInfo = errorDict;
return input;
} @catch (OtherException * e) {
....
} @finally {
// Any clean up can happen here.
// Finally will be called if an exception is thrown or not.
}
以及实际使用异常的链接:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Exceptions/Tasks/HandlingExceptions.html
关于iphone - iPhone-尝试,捕获问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6477416/