用swift处理异常

Bry*_*yon 7 exception-handling ios swift

我对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;
    }
Run Code Online (Sandbox Code Playgroud)

你应该怎么做/ try/catch来抛出像这样的异常的函数?

提前致谢.

布赖恩

Gor*_*ove 6

这是在Swift捕捉NSException中讨论的更普遍问题的特定情况。

总结似乎是迅速异常和objc异常是不同的。

在这种情况下,迅捷的文档说它抛出了一个Exception,但是无法捕获。至少听起来像是一个文档错误。

我不同意其他答案,因为缺少VC显然是程序员错误。如果行为如文献所述,则可以提出一种设计,在特定的情况下,根据VC是否存在,通用代码会做出不同的反应。必须添加其他配置以确保仅在存在VC时才尝试加载VC,这是对边缘案例漏洞等的邀请。cf更新异常。


Mid*_* MP 0

instantiateViewControllerWithIdentifier不是一个抛出函数,您无法使用 do...try...catch 来处理它如果视图控制器在故事板中不可用,则您无能为力。这是程序员的错误,造成这种错误的人应该处理此类问题。你不能将此类错误归咎于 iOS 运行时。

  • 感谢 Midhun 和@luk2302。这对于硬编码标识符来说非常有意义。对于数据驱动的标识符来说,这为应用程序的防弹留下了一些空白,但理解这种行为将推动正确的测试。谢谢! (2认同)