Closed. This question does not meet Stack Overflow guidelines 。它目前不接受答案。
想改善这个问题吗?更新问题,使其成为 Stack Overflow 的 on-topic。
7年前关闭。
Improve this question
我正在尝试从给定的 instagram 图片中获取字幕,但是如果没有字幕,该应用程序将引发异常并崩溃。我将如何实现
或者,如果这些是
或者,如果您有
有很多可能的方法,具体取决于您希望应用程序在这些情况下做什么,但异常处理无疑不是正确的方法。正如使用 Objective-C 编程指南的 Dealing With Errors 部分一样,异常旨在用于意外的“程序员错误”,而不是简单的逻辑错误,正如他们所说:
想改善这个问题吗?更新问题,使其成为 Stack Overflow 的 on-topic。
7年前关闭。
Improve this question
我正在尝试从给定的 instagram 图片中获取字幕,但是如果没有字幕,该应用程序将引发异常并崩溃。我将如何实现
@try
和 @catch
来做到这一点。这是我到目前为止所拥有的:@try {
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:[NSString stringWithFormat:@"%@",entry[@"user"][@"full_name"]] message:[NSString stringWithFormat:@"%@",text[@"caption"][@"text"]]];
[modal show];
}
@catch (NSException *exception) {
NSLog(@"Exception:%@",exception);
}
@finally {
//Display Alternative
}
最佳答案
这不是异常和 try
- catch
- finally
块的良好使用。你说如果标题是 nil
,你会得到异常。那么,为了优雅地处理这种情况,您到底希望您的应用做什么?根本不显示对话框?那么你可能会做这样的事情:
NSString *user = entry[@"user"][@"full_name"];
NSString *caption = text[@"caption"][@"text"];
if (caption != nil && caption != [NSNull null] && user != nil && user != [NSNull null]) {
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:user message:caption];
[modal show];
}
或者,如果这些是
nil
,也许您想显示其他内容:NSString *user = entry[@"user"][@"full_name"];
NSString *caption = text[@"caption"][@"text"];
if (caption == nil || caption == [NSNull null])
caption = @""; // or you might have @"(no caption)" ... whatever you want
if (user == nil || user == [NSNull null])
user = @"";
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:user message:caption];
[modal show];
或者,如果您有
RNBlurModalView
的源代码,也许您可以诊断为什么在标题为 nil
时它会产生异常,并在那里解决该问题。有很多可能的方法,具体取决于您希望应用程序在这些情况下做什么,但异常处理无疑不是正确的方法。正如使用 Objective-C 编程指南的 Dealing With Errors 部分一样,异常旨在用于意外的“程序员错误”,而不是简单的逻辑错误,正如他们所说:
关于ios - Try-Catch 错误目标 C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18093046/