【发布时间】:2016-04-03 08:59:46
【问题描述】:
我有一个关于 Swift 中的异常处理的问题。 UIStoryboard 类的 UIKit 文档指出,如果标识符为 nil 或故事板中不存在,则 instantiateViewControllerWithIdentifier( identifier: String ) -> UIViewController 函数将引发异常。但是,如果我使用如下所示的 do/try/catch,我会收到警告“在 'try' 表达式中没有调用抛出函数。”
这只是一个警告,所以我认为这是一个智能感知问题;但是当我运行以下代码并故意使用无效标识符时,不会捕获到异常并生成 SIGABRT。
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
do {
let controller = try storyboard.instantiateViewControllerWithIdentifier("SearchPopup")
// This code is only included for completeness...
controller.modalPresentationStyle = .Popover
if let secPopoverPresentationController = controller.popoverPresentationController {
secPopoverPresentationController.sourceView = self.view
secPopoverPresentationController.permittedArrowDirections = .Any
secPopoverPresentationController.barButtonItem = self.bSearchButton
}
self.presentViewController(controller, animated: true, completion: nil)
// End code included for completeness.
}
catch {
NSLog( "Exception thrown instantiating view controller." );
return;
}
对于像这样抛出异常的函数,你应该如何做/try/catch?
提前致谢。
布莱恩
【问题讨论】:
-
感谢您的快速回复。我的问题的重点在所有细节中都丢失了。文档说抛出了异常,但 XCode 警告说没有抛出异常 - 为什么有区别?
-
是的,你得到了 RuntimeException,但是对于静态函数不是这样。
-
对不起 - 我花了超过 5 分钟来写这篇文章,所以我重新发布。感谢您及时的回复。我的问题的重点在所有细节中都丢失了。文档说抛出了一个异常,但是 XCode 警告说没有抛出异常——为什么会有区别?我的 catch 没有模式,并且根据 Swift 语言参考“如果 catch 子句没有模式,则该子句匹配任何错误并将错误绑定到名为 error 的本地常量。”我看过你的帖子,我认为我所做的与你记录的内容没有什么不同。
-
这能回答你的问题吗? Catching NSException in Swift
标签: ios swift exception-handling