Swift中的try-catch异常 [英] try-catch exceptions in Swift
问题描述
是否可以在Swift中捕获异常?给出以下代码:
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()))
是否可以防止异常崩溃整个程序?也就是说,在Objective-C中Swift等同于以下内容:
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!"];
}
推荐答案
它没有异常处理,和开发人员论坛中的这个讨论讨论了为什么会这样:
但请记住,Cocoa和Cocoa Touch传统上并不打算
来捕捉异常;他们打算不要让他们首先抛出
。应该使用
可选类型和inout NSError参数来处理普通错误;你应该解决任何
的情况,导致断言失败(这似乎是Swift中唯一的
异常抛出机制)通过编写更好的代码。
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.
这篇关于Swift中的try-catch异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!