try-catch exceptions in Swift [duplicate]

房东的猫 提交于 2019-12-17 04:30:45

问题


Is it possible to catch exceptions in Swift? Given the following code:

NSException.raise(NSRangeException,
    format: "Now you've gone too far!",
    arguments: CVaListPointer(fromUnsafePointer: UnsafePointer()))

Is it possible to prevent the exception from crashing the entire program? That is, what is the Swift equivalent of the following in Objective-C:

@try {
    [NSException raise:NSRangeException format:@"Now you've gone too far!"];
}

回答1:


It doesn't have exception handling, and this discussion in the developer forum discusses why it may be so:

but keep in mind that Cocoa and Cocoa Touch traditionally don't intend for you to catch exceptions; they intend for you to not cause them to be thrown in the first place. Ordinary errors should be handled with optional types and inout NSError parameters; you should address any situation that causes an assertion to fail (which seems to be the only exception-throwing mechanism in Swift) by writing better code.




回答2:


I believe that, as of today, Swift does not support this. It will most likely be added on future betas.



来源:https://stackoverflow.com/questions/24023112/try-catch-exceptions-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!