这是我当前的代码
class HelloWorld {
func foobar() {
// ...
}
}
当调用此函数并发生意外情况时,我如何使该函数抛出异常?
最佳答案
根据 Swift 文档:
Throwing Errors
To indicate that a function or method can throw an error, you write the throws keyword in its declaration, after its parameters. If it specifies a return type, you write the throws keyword before the return arrow (->). A function, method, or closure cannot throw an error unless explicitly indicated.
Apple's documentation 中有大量关于此主题的信息
错误是使用枚举表示的,因此通过枚举创建一些您想要的错误,然后使用 throw
关键字来完成。
示例:
enum MyError: ErrorType{
case FooError
}
func foobar() throws{
throw MyError.FooError
}
关于swift - 如何使 Swift 2 函数抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31993665/